我在阅读/修改时遇到这个奇怪的问题,最后用openpyxl保存现有的xlsx文件。首先看一下我得到的错误信息:
Traceback (most recent call last):
...
File "/storage/share/qfotoka/general_main.py", line 260, in saveTestRecord
workbook.save(filepath)
File "/usr/lib/python2.7/site-packages/openpyxl-1.8.2/openpyxl/workbook.py", line 265, in save
save_workbook(self, filename)
File "/usr/lib/python2.7/site-packages/openpyxl-1.8.2/openpyxl/writer/excel.py", line 187, in save_workbook
writer.save(filename)
File "/usr/lib/python2.7/site-packages/openpyxl-1.8.2/openpyxl/writer/excel.py", line 170, in save
self.write_data(archive)
File "/usr/lib/python2.7/site-packages/openpyxl-1.8.2/openpyxl/writer/excel.py", line 98, in write_data
self._write_worksheets(archive, shared_string_table, self.style_writer)
File "/usr/lib/python2.7/site-packages/openpyxl-1.8.2/openpyxl/writer/excel.py", line 128, in _write_worksheets
style_writer.get_style_by_hash()))
File "/usr/lib/python2.7/site-packages/openpyxl-1.8.2/openpyxl/writer/worksheet.py", line 98, in write_worksheet
write_worksheet_cols(doc, worksheet, style_table)
File "/usr/lib/python2.7/site-packages/openpyxl-1.8.2/openpyxl/writer/worksheet.py", line 209, in write_worksheet_cols
col_def['style'] = str(style_table[hash(columndimension.style_index)])
KeyError: -8937945243006069197
正如您所看到的,我对xlsx文件做了很多事情。由于我的Excel文件中的max_cols是' E',我在E1-H3中添加了一些值。
这是我的sample.xlsx文件,抱歉还不能发布图片:
A B C D
Area Test Prio Selected ?
ZZZ ZZZ011 1.1.0 x
XXX XXX012 1.1.0 x
先谢谢。
我的代码:
from openpyxl import Workbook
from openpyxl import load_workbook
from openpyxl.style import Color, Fill
from openpyxl.cell import coordinate_from_string, column_index_from_string, Cell
def saveTestRecord(filepath, sheetName, results=None):
try:
workbook = load_workbook(filename=filepath,guess_types=False)
sheets = workbook.get_sheet_names()
for i in sheets:
if i == sheetName:
print "Sheet: %s found"%(i)
sheet = workbook.get_sheet_by_name(i)
except:
print "Problem reading excel file: %s or no sheet found with pattern: %s"%(filepath, sheetName)
exit
max_cols = 0.0
for row in sheet.rows:
max_cols = float(sheet.get_highest_column())
starting_col = chr(65 + int(max_cols))
if max_cols % 4.0 == 0.0: createNewResultsSet(sheet, starting_col)
workbook.save(filepath)
def createNewResultsSet(sheet, startPos):
sheet.cell(startPos + '1').value = ''
sheet.cell(startPos + '2').value = 'Started'
sheet.cell(startPos + '3').value = ''
nextPos = chr(ord(startPos) + 1)
sheet.cell(nextPos + '1').value = ''
sheet.cell(nextPos + '2').value = 'Ended'
sheet.cell(nextPos + '3').value = ''
nextPos = chr(ord(nextPos) + 1)
sheet.cell(nextPos + '1').value = 'Status'
sheet.cell(nextPos + '2').value = 'Verdict'
sheet.cell(nextPos + '3').value = ''
nextPos = chr(ord(nextPos) + 1)
sheet.cell(nextPos + '1').value = ''
sheet.cell(nextPos + '2').value = 'Note'