Unable to save file on XLWings - python

[USING XLWINGS PACKAGE]
I'm attempting to open an excel spreadsheet (existing), write data to specified cells, and then use the workbook.save() function to save the file to a new file name (as not to overwrite)
Right now I currently have:
app = xw.App(visible = False)
wbMain = wx.Book('Example.xlsm') #Open premade excel file
sheetMain = wbMain.sheets['Example']
sheetMain.range('A1').value = 'Test' #Modify value of cell A1
wbMain.save('NewFileName.xlsm') #Save to new filename
wbMain.close() #Close current excel sheet
app.kill() #Kill program (may not work)
(Sorry about my formatting if it's off)
Here is my traceback:
Traceback (most recent call last):
File "C:\Users\USER\Desktop\test_proj\main.py", line 34, in <module>
wbMain.save(NewFileName.xlsm)
----
File "C:\Users\USER\AppData\Local\Programs\Python\Python35\lib\site-
packages\xlwings\main.py", line 688, in save
return self.impl.save(path)
---
File "C:\Users\USER\AppData\Local\Programs\Python\Python35\lib\site-
packages\xlwings\_xlwindows.py", line 472, in save
self.xl.SaveAs(os.path.realpath(path))
----
File "C:\Users\USER\AppData\Local\Programs\Python\Python35\lib\site-
packages\xlwings\_xlwindows.py", line 63, in __call__
v = self.__method(*args, **kwargs)
---
File "<COMObject Open>", line 7, in SaveAs
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft
Excel', 'SaveAs method of Workbook class failed', 'xlmain11.chm', 0,
-2146827284), None)
I've tried lookin at the XLWings documentation and various other stackoverflow threads but none seemed to offer a solution that worked. Has anyone had the same issue before?

I had the same problem - turns out using the full path in wbMain.save('C:/xxx/NewFileName.xlsm') worked for me.
Credits to #aneroid for the help! See here: xlwings: Save and Close

Related

Error when closing an already open Excel file

I have a code to work with an already open Excel file (it actually just closes it so the rest of the code can work, and then opens it again at the end). It works in one of my computers, but not in the other - I'm getting the following error:
Traceback (most recent call last):
File "tkinter\__init__.py", line 1892, in __call__
file "executavel.py", line 48, in GetSquareRoot
File "site-packages\win32com\client\dynamic.py", line 527, in __getattr__
AttributeError: Excel.Application.Workbooks
Here is the part of the code that raises the error (line 48 is "wb = xlApp.Workbooks.Open(path)"):
xlApp = client.GetObject(None, "Excel.Application")
wb = xlApp.Workbooks.Open('planilha.xlsx')
wb.Save()
wb.Close()
All Excel windows are closed except for the spreadsheet in question (there are no open pop-ups or anything). Is there a way to make this code work in both computers, or another way to close an already open Excel workbook?
Thanks!

Running an Excel macro via Python? (New problem - saving)

I already saw this question in other link but I'm new here and i don't have reputation to comment there.
I made the script works and the macro run but when saving the file instead of just saving, it opens a excel pop-up asking if i confirm the changes. How do I save directly without opening this pop-up?
my code (edited):
import os.path
import win32com.client as wincl
if os.path.exists("C:\\Users\\peo_cpena\\Downloads\\excel.xlsx"):
try:
xl = wincl.Dispatch("Excel.Application")
xl.Workbooks.Open(os.path.abspath(
"C:\\Users\\peo_cpena\\Downloads\\excel.xlsx"))
xl.Application.Run("macro2.xlsm!Macro2")
xl.Application.Workbooks("excel.xlsx").Save()
xl.Application.DisplayAlerts = False
xl.Application.Workbooks("excel.xlsx").Quit(False)
del xl
except:
xl.Application.Quit()
print("It didn't work")
del xl
Removing the Try i received this error:
Traceback (most recent call last):
File "C:/Users/peo_cpena/PycharmProjects/Cursoemvideo/UOL/CalculoImpARG.py", line 14, in <module>
xl.Application.Workbooks("C:\\Users\\peo_cpena\\Downloads\\Vendas_por_Repasse_Aeria_Games_Europe_GmbH_01102020-31102020.xlsx").Save()
File "C:\Users\peo_cpena\PycharmProjects\Cursoemvideo\venv\lib\site-packages\win32com\client\dynamic.py", line 197, in __call__
return self._get_good_object_(self._oleobj_.Invoke(*allArgs),self._olerepr_.defaultDispatchName,None)
pywintypes.com_error: (-2147352567, 'Exceção.', (0, None, None, None, 0, -2147352565), None)
Try explicitly saving the workbook before closing it:
xl.Application.Workbooks("excel.xlsx").Save()
xl.Application.Workbooks("excel.xlsx").Close(False)

Faild to save a xlxs file twice with comments using openpyxl

This is my codes. When I try to save a xlxs with comments, It failed. How can I know when to save again.
from openpyxl import load_workbook
import datetime
filename = u"large_table.xlsx"
model = load_workbook(filename)
model.properties.lastPrinted = datetime.datetime.now()
model.save(filename)
model.properties.lastPrinted = datetime.datetime.now()
model.save(filename)
Traceback: It seems that self.workbook.vba_archive is set to None unexpectedly.
Traceback (most recent call last):
File "D:/h32workspace/trunk/event_editor/eric6/model/test_file.py", line 31, in <module>
model.save(filename)
File "C:\Python27\lib\site-packages\openpyxl\workbook\workbook.py", line 342, in save
save_workbook(self, filename)
File "C:\Python27\lib\site-packages\openpyxl\writer\excel.py", line 269, in save_workbook
writer.save(filename)
File "C:\Python27\lib\site-packages\openpyxl\writer\excel.py", line 251, in save
self.write_data()
File "C:\Python27\lib\site-packages\openpyxl\writer\excel.py", line 81, in write_data
self._write_worksheets()
File "C:\Python27\lib\site-packages\openpyxl\writer\excel.py", line 214, in _write_worksheets
self._write_comment(ws)
File "C:\Python27\lib\site-packages\openpyxl\writer\excel.py", line 184, in _write_comment
vml = fromstring(self.workbook.vba_archive.read(ws.legacy_drawing))
AttributeError: 'NoneType' object has no attribute 'read'
I tried to use keep_vba=True to load workbook, but if failed to save file correctly. The saved file can not be opened.
I used your code to save a sample .xlsx file. It saved without any issues.
Do you have any macro within you .xlsx file?
If yes, you may want to open the xlsx file with macro enabled using
model = load_workbook(filename, keep_vba=True)
See here for details on openpyxl usage with macro.
Also, try to save to a different filename than trying to overwrite original to make sure it works correctly.
fileout = "test2.xlsx"
model.save(fileout)
Hope this helps.

Error while loading excel file with Openpyxl

I am trying yo load an excel file using Openpyxl in Python.
from openpyxl import load_workbook
wb2 = load_workbook('Book1.xlsx')
print wb2.get_sheet_names()
It just these three lines. and it throws the following error:
Traceback (most recent call last):
File "C:/Python27/excel1.py", line 5, in <module>
wb2 = load_workbook('Book1.xlsx')
File "C:\Python27\Lib\site-packages\openpyxl\reader\excel.py", line 141, in load_workbook
archive = ZipFile(f, 'r', ZIP_DEFLATED)
File "C:\Python27\Lib\zipfile.py", line 793, in __init__
self._RealGetContents()
File "C:\Python27\Lib\zipfile.py", line 835, in _RealGetContents
raise BadZipfile, "File is not a zip file"
BadZipfile: File is not a zip file
This is exactly like their Documentation. https://openpyxl.readthedocs.org/en/latest/tutorial.html
Is their any better package to do this.
If this file does not exist at the desired location, try:
from openpyxl import load_workbook
from openpyxl import Workbook
# 1) create a workbook
wb = Workbook()
wb.save('my.xlsx')
del wb
# 2) build connection with the just created excel
book = load_workbook('my.xlsx')
It is an issue with the file. When we saved the file externally it was prompting this error. easy fix is to make a try catch and if the it gives the error create a new file in the same name and save on the same place. But for appending with old data wont work in this case.
try:
# this statement shall raise error for Badzip file
wb_obj = openpyxl.load_workbook(filename=path)
except:
# try to create a new file and save at same path
wb_obj = openpyxl.Workbook()
wb_obj.save(path)
wb_obj = openpyxl.load_workbook(filename=path)
xlsx files are zip archives. It looks like the file you're trying to open isn't. If you think this isn't the case please submit a but with a sample file.

xlrd cannot read xlsx file downloaded from email attachment

This is a very very strange issue. I have quite a large excel file (the contents of which I cannot discuss as it is sensitive data) that is a .xlsx and IS a valid excel file.
When I download it from my email and save it on my desktop and try to open the workbook using xlrd, xlrd throws an AssertionError and does not show me what went wrong.
When I open the file using my file browser, then save it (without making any changes), it works perfectly with xlrd.
Has anyone faced this issue before? I tried passing in various flags to the open_workbook function to no avail and I tried googling for the error. So far I haven't found anything.
The method I used was as follows
file = open('bigexcelfile.xlsx')
fileString = file.read()
wb = open_workbook(file_contents=filestring)
Please help! The error is as follows
Traceback (most recent call last):
File "./varify/samples/resources.py", line 354, in post
workbook = xlrd.open_workbook(file_contents=fileString)
File "/home/vagrant/varify-env/lib/python2.7/site-packages/xlrd/__init__.py", line 416, in open_workbook
ragged_rows=ragged_rows,
File "/home/vagrant/varify-env/lib/python2.7/site-packages/xlrd/xlsx.py", line 791, in open_workbook_2007_xml
x12sheet.process_stream(zflo, heading)
File "/home/vagrant/varify-env/lib/python2.7/site-packages/xlrd/xlsx.py", line 528, in own_process_stream
self_do_row(elem)
File "/home/vagrant/varify-env/lib/python2.7/site-packages/xlrd/xlsx.py", line 722, in do_row
assert tvalue is not None
AssertionError
rename or Save as your Excel file as .xls instead of .xlsx
Thank You
Use pyopenxl, not xlrd, for this format: https://openpyxl.readthedocs.org/en/latest/

Categories