Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

openpyxl 2.4.2: cell value generated by formula empty after saving

I use openpyxl to open a file, edit some cells and save the changes. Here's an example:

  import openpyxl
  book = openpyxl.load_workbook(sheet_path)    
  sheet = book.active

  for row in range(sheet.max_row):
      index = row + 1
      sheet.cell(row=index, column=1).value = "something"

  book.save(sheet_path)

The problem is, when I save the file, other cells are modified. In fact, the cells in my sheet that contains formulas are "corrupted", the file size is greatly reduced and when I use other scripts to read the sheet, the cells containing formulas are reported as empty. But when I open the sheet, everything looks normal and when I save, everything is repaired and the file size is back to normal. I think the problem comes from openpyxl not "calculating" the formulas when saving. This would reduce the file size and require a manual opening/saving in order to get the real cell values. I can't find any way to resolve this issue without completely changing the library I use. Any help would be appreciated, thanks!

like image 776
Léandre Arseneault Avatar asked Oct 29 '22 11:10

Léandre Arseneault


1 Answers

When openpyxl reads and writes existing formulas, the computed values are omitted, and no values are computed for new formulas. openpyxl sets a flag in the workbook that tells excel to recompute formula values on load, which is why everything looks normal when you look at it with excel.

like image 125
cco Avatar answered Nov 15 '22 06:11

cco