I want to write a new workbook, with 1 sheet and add a table to that sheet. AFAIK it should be possible, this commit should do it https://bitbucket.org/openpyxl/openpyxl/commits/6f440b0ed398
But when I try to do that, it fails with the message:
KeyError: 'Unknown relationship: None'
My code snippet is:
from openpyxl import Workbook
from openpyxl.worksheet.table import Table
wb = Workbook(write_only=True)
ws = wb.create_sheet()
ws.append(['col1','col2','col3','col4'])
ws.append(['val11','val12','val13','val14'])
ws.append(['val21','val22','val23','val24'])
ws.append(['val31','val32','val33','val34'])
ws.append(['val41','val42','val43','val44'])
table = Table(displayName="basetable", ref="A1:D4")
ws.add_table(table)
wb.save('table.xlsx')
The full traceback is:
File "<stdin>", line 1, in <module>
wb.save('table.xlsx')
File "./site-packages/openpyxl/workbook/workbook.py", line 354, in save
save_dump(self, filename)
File "./site-packages/openpyxl/writer/excel.py", line 313, in save_dump
writer.save(filename)
File "./site-packages/openpyxl/writer/excel.py", line 266, in save
self.write_data()
File "./site-packages/openpyxl/writer/excel.py", line 83, in write_data
self._write_worksheets()
File "./site-packages/openpyxl/writer/excel.py", line 229, in _write_worksheets
ws._rels[t._rel_id].Target = t.path
File "./site-packages/openpyxl/packaging/relationship.py", line 97, in __getitem__
raise KeyError("Unknown relationship: {0}".format(key))
Question: write-only worksheet fails to add table
Tried your Example got:
AttributeError: 'WriteOnlyWorksheet' object has no attribute 'add_table'
Removed write_only=True, works OK.
Output:
Tested with Python: 3.4.2 and 2.7.9 - openpyxl: 2.4.1 - LibreOffice: 4.3.3.2
Related
Here is my code to import an excel sheet and edit it:
import openpyxl as xl
wb = xl.load_workbook('transactions.xlxs')
sheet = wb['Sheet1']
cell = sheet['a1']
cell = sheet.cell(1, 1)
print(cell.value)
However I get the following error message:
C:\Users\mirco\PycharmProjects\pythonProject14\venv\Scripts\python.exe C:/Users/mirco/PycharmProjects/pythonProject14/main.py
Traceback (most recent call last):
File "C:\Users\mirco\PycharmProjects\pythonProject14\main.py", line 2, in <module>
wb = xl.load_workbook('transactions.xlxs')
File "C:\Users\mirco\PycharmProjects\pythonProject14\venv\lib\site-packages\openpyxl\reader\excel.py", line 315, in load_workbook
reader = ExcelReader(filename, read_only, keep_vba,
File "C:\Users\mirco\PycharmProjects\pythonProject14\venv\lib\site-packages\openpyxl\reader\excel.py", line 124, in __init__
self.archive = _validate_archive(fn)
File "C:\Users\mirco\PycharmProjects\pythonProject14\venv\lib\site-packages\openpyxl\reader\excel.py", line 94, in _validate_archive
raise InvalidFileException(msg)
openpyxl.utils.exceptions.InvalidFileException: openpyxl does not support .xlxs file format, please check you can open it with Excel first. Supported formats are: .xlsx,.xlsm,.xltx,.xltm
Process finished with exit code 1
How can I fix this?
wb = xl.load_workbook('transactions.xlxs')
was supposed to be
wb = xl.load_workbook('transactions.xlsx')
a little dyslexic mistake
also had to move excel file to the right location
Beginner here.
I've tried making new excel files, running the python code while the excel file is open, tried renaming the excel file, but nothing works. I was just following this youtube tutorial: https://www.youtube.com/watch?v=7YS6YDQKFh0&t=14s
from openpyxl import Workbook, load_workbook
workbook = load_workbook("Test2.xlsx")
The error:
Traceback (most recent call last):
File "c:\Users\Name\Desktop\Python Projects\Excel Manipulation\Excel_Test.py", line 3, in <module>
workbook = load_workbook("Test2.xlsx")
File "C:\Users\Name\AppData\Local\Programs\Python\Python39\lib\site-packages\openpyxl\reader\excel.py", line 315, in load_workbook
reader = ExcelReader(filename, read_only, keep_vba,
File "C:\Users\Name\AppData\Local\Programs\Python\Python39\lib\site-packages\openpyxl\reader\excel.py", line 124, in __init__
self.archive = _validate_archive(fn)
File "C:\Users\Name\AppData\Local\Programs\Python\Python39\lib\site-packages\openpyxl\reader\excel.py", line 96, in _validate_archive
archive = ZipFile(filename, 'r')
File "C:\Users\Name\AppData\Local\Programs\Python\Python39\lib\zipfile.py", line 1239, in __init__
self.fp = io.open(file, filemode)
**FileNotFoundError: [Errno 2] No such file or directory: 'Test2.xlsx'
PS C:\Users\Name>**
I found a solution. Turns out you just need to copy the file location, convert it to raw string, and add \ExcelFile to the end:
from openpyxl import Workbook, load_workbook
location = r'C:\Users\Name\Desktop\Python Projects\Excel Manipulation\Test2.xlsx'
workbook = load_workbook(location)
Derp.
I'm attempting to open an xlsx-file using load_workbook from the module openpyxl. The code I have is:
import os
from openpyxl import load_workbook
def edit_workbook():
path = r'C:\123 ABC\Excel documents'
filename = 'filename.xlsx'
os.path.join(path, filename)
workbook = load_workbook(os.path.join(path, filename))
## Error is on the line above.
The complete error message I get is:
Traceback (most recent call last):
File "<ipython-input-12-22dfdfc4e5e1>", line 1, in <module>
workbook = load_workbook(os.path.join(path, filename))
File "C:\Users\Stewie\Anaconda3\lib\site-packages\openpyxl\reader\excel.py", line 214, in load_workbook
apply_stylesheet(archive, wb) # bind styles to workbook
File "C:\Users\Stewie\Anaconda3\lib\site-packages\openpyxl\styles\stylesheet.py", line 176, in apply_stylesheet
stylesheet = Stylesheet.from_tree(node)
File "C:\Users\Stewie\Anaconda3\lib\site-packages\openpyxl\styles\stylesheet.py", line 99, in from_tree
return super(Stylesheet, cls).from_tree(node)
File "C:\Users\Stewie\Anaconda3\lib\site-packages\openpyxl\descriptors\serialisable.py", line 79, in from_tree
obj = desc.expected_type.from_tree(el)
File "C:\Users\Stewie\Anaconda3\lib\site-packages\openpyxl\descriptors\serialisable.py", line 79, in from_tree
obj = desc.expected_type.from_tree(el)
File "C:\Users\Stewie\Anaconda3\lib\site-packages\openpyxl\descriptors\serialisable.py", line 79, in from_tree
obj = desc.expected_type.from_tree(el)
File "C:\Users\Stewie\Anaconda3\lib\site-packages\openpyxl\descriptors\serialisable.py", line 92, in from_tree
return cls(**attrib)
File "C:\Users\Stewie\Anaconda3\lib\site-packages\openpyxl\styles\table.py", line 37, in __init__
self.dxfId = dxfId
File "C:\Users\Stewie\Anaconda3\lib\site-packages\openpyxl\descriptors\base.py", line 69, in __set__
value = _convert(self.expected_type, value)
File "C:\Users\Stewie\Anaconda3\lib\site-packages\openpyxl\descriptors\base.py", line 59, in _convert
raise TypeError('expected ' + str(expected_type))
TypeError: expected <class 'int'>
Anyone know what this can be?
I received the same error. In my case, the Excel workbook has no charts, no filters, no formulas, no VBA. Only data. This workbook was generated by some third party software.
Turns out that the workbook was corrupted. I found that out when trying to save it after some very minor change. Once I resolved the corruption (by letting Excel save it to a different name as it requested), the openpyxl error disappeared.
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.
I have a xlsx file and I tried to load this file using openpyxl
from openpyxl import load_workbook
wb = load_workbook('/home/file_path/file.xlsx')
But I get this error:
"wb = load_workbook(new_file)"): expected string or buffer
new_file is a variable with the path of the xlsx file trying to open. Does anybody knows why this happens or how I should change to read the file? Thanks!
Update More details about the error
/home/vagrant/scrapy/local/lib/python2.7/site-packages/openpyxl/reader/worksheet.py:322: UserWarning: Unknown extension is not supported and will be removed
warn(msg)
/home/vagrant/scrapy/local/lib/python2.7/site-packages/openpyxl/reader/worksheet.py:322: UserWarning: Conditional Formatting extension is not supported and will be removed
warn(msg)
Traceback (most recent call last):
File "/vagrant/vagrant_conf/pycharm-debug.egg/pydevd_comm.py", line 1071, in doIt
result = pydevd_vars.evaluateExpression(self.thread_id, self.frame_id, self.expression, self.doExec)
File "/vagrant/vagrant_conf/pycharm-debug.egg/pydevd_vars.py", line 344, in evaluateExpression
Exec(expression, updated_globals, frame.f_locals)
File "/vagrant/vagrant_conf/pycharm-debug.egg/pydevd_exec.py", line 3, in Exec
exec exp in global_vars, local_vars
File "<string>", line 1, in <module>
File "/home/vagrant/scrapy/local/lib/python2.7/site-packages/openpyxl/reader/excel.py", line 252, in load_workbook
wb._named_ranges = list(read_named_ranges(archive.read(ARC_WORKBOOK), wb))
File "/home/vagrant/scrapy/local/lib/python2.7/site-packages/openpyxl/workbook/names/named_range.py", line 130, in read_named_ranges
if external_range(node_text):
File "/home/vagrant/scrapy/local/lib/python2.7/site-packages/openpyxl/workbook/names/named_range.py", line 112, in external_range
m = EXTERNAL_RE.match(range_string)
TypeError: expected string or buffer
The syntaxe is:
wb = load_workbook(filename='file.xlsx', read_only=True)
The read_only keyword is not required.