I want to write some data from a CSV to an Excel-Sheet.
Here is my Code:
import xlrd
import xlsxwriter
import requests
# download
link="...."
s=requests.get(link).content
c=pd.read_csv(io.StringIO(s.decode('utf-8')))
book = xlrd.open_workbook("***.xlsx","w")
worksheet = book.sheet_by_index(10)
worksheet.write('B2',5)
workbook.close()
Actually i want to use the data from the requested link. But the code still stops on write a simple Issue. It works if i add a new sheet. But i cant write in an existing sheet. Have anyone an idea?
Related
Trying to save an xlsx file and include the current date in the file name during the process. Currently, I'm using the below code but I receive the error invalid format string - uncertain what format I can use to accomplish this.
I saw this method recommended in another thread but it doesn't work for me. I've tried several other solutions as well but nothing seems to work. Any guidance would be appreciated.
from openpyxl import load_workbook
from datetime import datetime, date
import os
from glob import glob
import pandas as pd
file = glob(
'C:\\Users\\all*.xlsx')[0]
wb1 = load_workbook(file)
ws1 = wb1.worksheets[0]
for row in ws1['A2':'D5']:
for cell in row:
cell.value = None
wb1.save('file1'+now.strftime("%Y%m%d%")+'.xlsx')
The error is in the save command where you have an extra % in the end. Also, just now is not sufficient, it needs the (). For the code above, think it also needs the datetime. to be added. So, change the last line from....
wb1.save('file1'+now.strftime("%Y%m%d%")+'.xlsx')
to
wb1.save('file1'+datetime.now().strftime("%Y%m%d")+'.xlsx')
I have a dataframe called results and an excel file named as vlpandas.xlsx. I set a default path for working dir as follows:
excel_dir = 'Users/Documents/Pythonfiles'
Based on the example from this post,: How to save a new sheet in an existing excel file, using Pandas?, I did the following:
book = load_workbook(excel_dir)
But I an error above after running the command, to fix it I use the usage as documented from the openpyxl and the following works:
book = load_workbook(filename = 'vlpandas.xlsx')
But then I get an exception error when I run the command below. Something about workbook.py from the openpyxl directory.
writer = pd.ExcelWriter(excel_dir, engine='openpyxl')
and then I want to complete my task saving the data to the new worksheet in the existing file vlpandas.xlsx with the following lines of code:
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
## Your dataframe to append.
results.to_excel(writer, '3rd_sheet')
writer.save()
So my two questions are:
1) What is the proper usage of load_Workbook from openpyxl
2) Why I am I getting an error with the command line below. I also changed my working folder path using the command osc.chdir:
writer = pd.ExcelWriter(excel_dir, engine='openpyxl')
Regards,
Gus
Hi I have a pretty complex spreadsheet and I need to update "ONLY" certain part of its contents.
I tried openpyxl, which works ok except all the pivot tables, styles and formulas are lost, after save the workbook. Is there a way to get around that?
Check which version of openpyxl you have installed. Support for Pivot Tables was only added in version 2.5.0-a1 (2017-05-30), and that only supported one Pivot Table until version 2.5.0-b2 (2018-01-19). See changelog.
Alternatives: Simplify, xlwings, content protection, and win32com (most likely).
If you are using 2.5 and it doesn't work, you'll probably have to simplify your spreadsheet if you want to continue to use openpyxl. E.g. split it into a source and output file, and use python to update the source file.
You could try running xlwings to host the Python code inside of the spreadsheet itself.
Another possible solution would be to lock the contents - turn on protection - for all except the sections you plan to update. This is unlikely to work as python is changing the contents directly, but it may respect the lock.
Finally, the result most likely to work. Drive the changes through the win32com module. I think this, unlike openpyxl, requires Excel to be installed as it is using Excel's functionality to make the changes. Examples of usage are here and here.
A brief example (taken from here):
import win32com.client as win32
excel = win32.gencache.EnsureDispatch('Excel.Application')
wb = excel.Workbooks.Add()
ws = wb.Worksheets("Sheet1")
ws.Cells(1,1).Value = "Cell A1"
ws.Cells(1,1).Offset(2,4).Value = "Cell D2"
ws.Range("A2").Value = "Cell A2"
ws.Range("A3:B4").Value = "A3:B4"
ws.Range("A6:B7,A9:B10").Value = "A6:B7,A9:B10"
wb.SaveAs('ranges_and_offsets.xlsx')
excel.Application.Quit()
I have a small project where data from Oracle SQL Developer needs to be exported to Excel (using commands rather than tools in SLQ Developer), then create a graph.
Using "spool" I can export to csv fine (but cant make a graph in csv) but when I try to export to xlsx it corrupts the whole excel sheet saying
"Excel cannot open the file "ExcelFile.xlsx" because the file format or file extention
is not valid. Verify that the file has not been corrupted and that the
file extension mathces the format of the file."
Here is the code I used in SQL Developer.
spool FileLocation\ExcelFile.xlsm
SELECT * FROM Table;
spool off;
Is there any way I can stop the data from becoming corrupted or is there another way to export data to a .xlsx file?
Nooooooo.
set sqlformat csv
spool c:\file.sql
select * from table;
spool off;
then open the file in excel.
OR
Run your query interactively.
Right click on the grid, Export > XLSX. Open the file.
Spool only writes the query output to the file, it doesn't look at the file extension and figure out HOW to write the output at that point.
So you either have to code it yourself via the query, or use one of the format outputs we support
SET SQLFORMAT
CSV
JSON
DELIMITED
XML
HTML
INSERT
LOADER
Use 'help set sqlformat' for help.
Hi sql developer from what I know for exporting is using sqlplus(code is same) so perhabs there are other ways but this one should be good enough
I would try changing first line to look like this:
spool ExcelFile.xls
Probably you also need to turn on
SET MARKUP HTML ON
http://www.orahow.com/2015/09/spool-sqlplus-output-to-excel-format.html
Anyway there is workaround - you can just generate .CSV file and then open it in excel and save as .xlsx file
I was also facing the same problem then applied below code and it exported successfully..
import xlsxwriter
from xlsxwriter import Workbook
import cx_Oracle
import datetime
from datetime import date
dsn_tns = cx_Oracle.makedsn('HOST', 'PORTNO', sid='BGRDB')
db = cx_Oracle.connect(user=r'username', password='password', dsn=dsn_tns)
cursor = db.cursor()
workbook = xlsxwriter.Workbook('C:/Path/outfile.xlsx')
sheet = workbook.add_worksheet()
cursor.execute("select * from TABLENAME")
for r, row in enumerate(cursor.fetchall()):
for c, col in enumerate(row):
sheet.write(r, c, col)
workbook.close()
cursor.close()
I need to import exchange rate data stored in an Excel spreadsheet online into an Access data table. However first I need to manipulate it so I would like to import it into an array and then write the array to the table. The code I used for Excel doesn't seem to work with Access...
Dim arr as variant
Workbook.Open ("http://www.rba.gov.au/statistics/tables/xls-hist/f11hist.xls")
arr=activeworkbook.worksheets("Data").Range("A12:X" & Range("A1045876").end(xldown).Row)
'data manipulation ommitted
'add to data table
Clearly this doesn't work in Access, but I've got no idea how to open the file and read the data. Any help appreciated!
Your question is overly broad, so the answer is generic. You can use Microsoft Excel object library in MS Access application by adding the reference to that library and start using its methods, similar to what you have done in Excel. More details in: https://msdn.microsoft.com/en-us/library/office/ff194944.aspx. Hope this may help.
I guess this line can help you.
Docmd.Transferspreadsheet acImport,,"name of excel table","link to find the table (ex:c:.....)",true
that will help to take a excel table and import its on access .
Excel does this by - behind the scene - first downloading the file then reading it.
Access can't do this, but you can use VBA to download the file Download file from URL and then create a link to a Worksheet or a Named Range in it. Or open the file via automation.