Question

I'm generating one Excel with a template,

from openpyxl import Workbook
from openpyxl import load_workbook

src_file = 'D:\\code\\TestLink-Report\\pyxl.xlsx'
wb = load_workbook(filename = src_file, guess_types = False)

sheet = wb.worksheets[0]
sheet.cell('A1').value = 'blabla'
wb.save(filename =  src_file)

If src_file is new blank one, it works. If I change width of any column in src file by manual, run code again, it fails

    wb.save(filename =  src_file)
  File "D:\Python27\envs\TestLink\lib\site-packages\openpyxl\workbook.py", line 265, in save
    save_workbook(self, filename)
  File "D:\Python27\envs\TestLink\lib\site-packages\openpyxl\writer\excel.py", line
 187, in save_workbook
    writer.save(filename)
  File "D:\Python27\envs\TestLink\lib\site-packages\openpyxl\writer\excel.py", line
 170, in save
    self.write_data(archive)
  File "D:\Python27\envs\TestLink\lib\site-packages\openpyxl\writer\excel.py", line
 98, in write_data
    self._write_worksheets(archive, shared_string_table, self.style_writer)
  File "D:\Python27\envs\TestLink\lib\site-packages\openpyxl\writer\excel.py", line
 128, in _write_worksheets
    style_writer.get_style_by_hash()))
  File "D:\Python27\envs\TestLink\lib\site-packages\openpyxl\writer\worksheet.py", line 98, in write_worksheet
    write_worksheet_cols(doc, worksheet, style_table)
  File "D:\Python27\envs\TestLink\lib\site-packages\openpyxl\writer\worksheet.py", line 209, in write_worksheet_cols
    col_def['style'] = str(style_table[hash(columndimension.style_index)])
KeyError: 549131827

I'm using Excel 2013. I heard openpyxl doesn't support style well after searching on stackoverflow. But my problem seems that it should be one simple thing.

Was it helpful?

Solution

This issue has been resolved here

run this to get the latest version

hg clone https://bitbucket.org/ericgazoni/openpyxl
cd openpyxl/
hg up 1.8
python setup.py develop

OTHER TIPS

Is it possible to use win32com as an option? A simple column formatting can be done there like below:

from win32com.client import Dispatch

xl = Dispatch("Excel.Application")
filestr = "C:\blah\pytest.xlsx"
wbk = xl.Workbooks.Open(filestr)

wsht = wbk.Sheets(1)
wsht.Range("A1").Value = "Hello World!"
wsht.Columns(1).ColumnWidth = 50
wbk.SaveAs("C:\blah\pytested.xlsx")

xl.Application.Quit()

You can use it in conjunction with openpyxl if you just need to adjust column widths.

Let us know if this helps. :)

There is currently work going on in openpyxl to resolve the error you're getting. Both the 1.8 and 1.9 branches will currently prevent it happening but the resulting Excel files may not be usable.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top