What I want to do is to open csv file, make changes inside and save it. My code looks like this:
savePath = r'D:\file.csv'
with xw.App(visible=True) as app:
wb = app.books.open(savePath)
sheet1 = wb.sheets[0]
saveDF = sheet1.range(wb.sheets[0].used_range.address).options(pd.DataFrame, chunksize=30_000, index=False).value
wb.sheets[0].clear()
wb.sheets[0].range('A1').options(index=False, header=True).value = saveDF
wb.api.SaveAs(savePath, FileFormat=FileFormat.xlCSV)
This code kinda works but when it saves the file it asks me if i want to overwrite the file since it already exists.
So what I did was to save it as "csv.txt" file, then remove the ".csv" file and rename ".csv.txt" file back to ".csv" file using code below:
savePath = r'D:\file.csv'
with xw.App(visible=True) as app:
wb = app.books.open(savePath)
sheet1 = wb.sheets[0]
saveDF = sheet1.range(wb.sheets[0].used_range.address).options(pd.DataFrame, chunksize=30_000, index=False).value
wb.sheets[0].clear()
wb.sheets[0].range('A1').options(index=False, header=True).value = saveDF
wb.api.SaveAs(savePath + '.txt', FileFormat=FileFormat.xlCSV)
os.remove(savePath)
os.rename(savePath + '.txt', savePath)
Issue I have here is that I get error:
"PermissionError: [WinError 32] The process cannot access the file because it is being used by another process:"
Which means that Python tries to rename files while its being saved.
So my questions are:
Is there a way to overwrite csv file without needing to manually click "file already exists - do You want ot ovewrite it" prompt ?
Is there anything I can change in my code to not get [WinError 32] shown above ?
How can I change my code to not open two instances of excel (now it opens blank one - probably when I use "with" statement and second one with my file when I use app.books.open) ?
Thank You in advance for any kind of help.
I had the same problem caused by corrputed excel file saved by Excel Writer.
If you are writing an excel file in previous lines with pd.ExcelWriter and later you use the same file for xlwings, use context manager for Writer.
You don't have to overwrite the file by xlwings, you can simple do: wb.save(path=None). It will save the same file under the same name.
Just be attentive on the file you re using if it is a healty excel file - I mean not corrupted.
I'm quite new to xlwings and I'm runing code from VBA in order to excecute a python script that writes some text in Excel.
The problem is when I run the VBA code, it seems to excecute python but my excel sheet doesn't change.
However, if I run the python script from python, it works just fine, even if the Excel file is already open.
VBA code is the following:
Sub Botón1()
Dim obj As Object
Dim pyexe, pyscript As String
Set obj = VBA.CreateObject("Wscript.Shell")
pyexe = """C:\Users\xxx\AppData\Local\Programs\Python\Python36-32\python.exe"""
pyscript = "C:\Users\xxx\Documents\Prueba.py"
obj.Run pyexe & pyscript, 1, True
End Sub
And python code is the following:
import xlwings as xw
wb = xw.Book('Libro1.xlsm')
sht = wb.sheets['Hoja1']
sht.range('A1').value = 'Hi!'
Both files (Libro1.xlsm and Prueba.py) are saved inside the same folder.
When I run excel macro it opens the cmd prompt but nothing happens in Excel spreasheet.
I have not installed xlwings add in, but I believe it is not necessary to do it, in order to do what I'm trying to do.
Can you please help me find what could be wrong?
I was reading this article:
https://devblogs.microsoft.com/scripting/how-can-i-get-the-command-window-to-stay-open-after-running-a-command-line-tool/
And it explains using .run is equivalent to calling Cmd.exe.
If I open cmd I just need to write my python file name with .py extension to run it.
So I figured out "pyexe" is not necessary.
The solution:
Sub Botón1_Haga_clic_en()
Dim obj As Object
Set obj = CreateObject("Wscript.Shell")
obj.Run "C:\Users\xxx\Documents\Prueba.py", 1, True
End Sub
I am trying to run Excel macros from ABAQUS software tool which has inbuilt Python.
I have a default Excel file, I want this as a main Excel file and to make a new Excel file depending on the output database file.
I access the ABAQUS output data base file and get its name and make a new Excel file named by combining the output data base file name plus some other name.
I copy the main Excel file to this new Excel file.
I am able to open this newly created file, but I am unable to run the macros.
Here is the code with comments.
I get the path of my file with name and extension
filePath = odbFile.path
Filename with extension only
filename_w_ext = os.path.basename(filePath)
odbfilename,odbfileExtension = os.path.splitext(filename_w_ext)
excel_filename='abc.xlsm'
odbfilename+'_FAT'+'.xlsm'
newExcelFile = odbfilename+'_FAT'+'.xlsm'
shutil.copy(excel_filename, newExcelFile)
I access the win32client to access the Excel application
xl = win32com.client.Dispatch("Excel.Application")
Opening the Excel file, give the file path
xl.Workbooks.Open(newExcelFile)
Say newExcelFile created name is new.xlsm.
To run the Excel macros using PYTHON, the default code is
xl.Application.Run("excelName!ModuleNumberOfTheMacro.MacroName")
Run my macro to import nodes from Excel
xl.Application.Run("newExcelFile!Module1.ImporterFichiersTextes")
I put down the same format but Python is looking for the Excel sheet 'newExcelFile', instead of new.xlsm.
Where does Xlsxwriter save the files you have created? Is it possibly to specify the path where I want the excel files to be saved?
My XlsxWriter script was in file /app/smth1/smth2/ and for some reason it saved the excel file to /app/. Shouldn't it have saved it in the same file where the script was? Or do I have to specify the path like this:
workbook = xlsxwriter.Workbook(' /app/smth1/smth2/Expenses01.xlsx')
What is the default file where the excel file is saved?
Here's how you can save the file to the current directory (where your script is running from):
workbook = xlsxwriter.Workbook('demo.xlsx')
Here's how you can specify a full path:
workbook = xlsxwriter.Workbook('C:/Users/Steven/Documents/demo.xlsx')
Here's how you can specify a relative path:
workbook = xlsxwriter.Workbook('app/smth1/smth2/Expenses01.xlsx')
Note that a starting "/" is not needed and may cause errors.
More examples can be found here
I am trying to open a xlsx file and just print the contents of it. I keep running into this error:
import xlrd
book = xlrd.open_workbook("file.xlsx")
print "The number of worksheets is", book.nsheets
print "Worksheet name(s):", book.sheet_names()
print
sh = book.sheet_by_index(0)
print sh.name, sh.nrows, sh.ncols
print
print "Cell D30 is", sh.cell_value(rowx=29, colx=3)
print
for rx in range(5):
print sh.row(rx)
print
It prints out this error
raise XLRDError('Unsupported format, or corrupt file: ' + msg)
xlrd.biffh.XLRDError: Unsupported format, or corrupt file: Expected BOF record; found '\xff\xfeT\x00i\x00m\x00'
Thanks
If you use read_excel() to read a .csv you will get the error
XLRDError: Unsupported format, or corrupt file: Expected BOF record;
To read .csv one needs to use read_csv(), like this
df1= pd.read_csv("filename.csv")
There is also a third reason. The case when the file is already open by Excel.
It generates the same error.
The error message relates to the BOF (Beginning of File) record of an XLS file. However, the example shows that you are trying to read an XLSX file.
There are 2 possible reasons for this:
Your version of xlrd is old and doesn't support reading xlsx files.
The XLSX file is encrypted and thus stored in the OLE Compound Document format, rather than a zip format, making it appear to xlrd as an older format XLS file.
Double check that you are in fact using a recent version of xlrd. Opening a new XLSX file with data in just one cell should verify that.
However, I would guess the you are encountering the second condition and that the file is encrypted since you state above that you are already using xlrd version 0.9.2.
XLSX files are encrypted if you explicitly apply a workbook password but also if you password protect some of the worksheet elements. As such it is possible to have an encrypted XLSX file even if you don't need a password to open it.
Update: See #BStew's, third, more probable, answer, that the file is open by Excel.
You can get this error when the xlsx file is actually html; you can open it with a text editor to verify this. When I got this error I solved it using pandas:
import pandas as pd
df_list = pd.read_html('filename.xlsx')
df = pd.DataFrame(df_list[0])
to anyone who is reading this post today, the following solution actually helped me.
https://stackoverflow.com/a/46214958/9642876
The XLSX file that I was trying to read was created by a reporting software and it couldn't be read either by pandas or xlrd, but could open it in Microsoft Excel. I re-saved the file under a different name and now it both xlrd and pandas can read the file.
It may also work if you just re-save with the same name, although I haven't tested this.
In my case, someone gave me an Excel file ending with extension ".xls". I tried parsing it with xlrd, and got this error:
xlrd.biffh.XLRDError: Unsupported format, or corrupt file: Expected BOF record; found "blar blar blar"
After working some time, I found that .xls file actually is a text file. The sender didn't bother to create a real Excel binary file but just put ".xls" to a text file.
Maybe it's worth opening the file with text editor to make sure it is an Excel file. This could have saved me one hour.
In my case, the issue was with the shared folder itself.
CASE IN POINT: I have a shared folder on WIN2012 Server where the user drops the .xlsx file and then uses my python script to load that xlsx file into a database table.
Even though, the user deleted the old file and put in the file that was to be loaded, the BOF error kept mentioning a byte string and the name of the user in the byte string -- no where inside of the xlsx file in any worksheet was there the name of the user. On top of it, when I copied the .xlsx into a newly created folder and ran the script referencing that new folder, it worked.
So in the end, I deleted the shared folder and realized that 5 items got deleted even though only 1 item was visible to me and the user. I think it is down to my lack of windows administration skills but that was the culprit.
I got the same error message. It looks so weird to me because the script works for the xlsx files under another folder and the files are almost the same.
I still don't know why this happened. But finally, I copied all the excel files to another folder and the script worked. An option to try if none of the above suggestions works for you...
This also happens when the file used by script is also open in the background.