2

I have an XLSM File, where I need to edit some Cell Values with PHP. As I couldn't find a proper library, which can actually edit an xlsm file (most read excel and create a whole new excel file, which in this case would delete the macros inside the excel or even throw too many exceptions), I decided to unzip the xlsm file and directly edit the worksheet xml file by changing the values in the cells:

<c r="K15" s="52">
   <v>83221.56</v>
</c>

For example I would change the Value inside the "v" Tag.

As Simple XML doesnt work, because it messes up some namespaces inside the file, I decided to edit it with Regular Expressions.

So far so good - i got the change in the file. But Formulars inside the Excel file, that depend on the cell I just changed the Value in won't recognize my change. When you open the Excel file, it properly shows the correct value, but other cells that use that changed value in their formula won't update.

Does anyone have any idea how to properly change the XML File and keeping the excel in tact?

Thanks!

Niklas Riecken
  • 303
  • 1
  • 6
  • 20

1 Answers1

1

As I could not figure out a solution in PHP and previous solutions with C++ (Is there a PHP library for XLSM(Excel with Macro) parsing/editing?) where to complicated for me, I found a solution with python, I want to share.

My environment is Ubuntu 16.04, I have Python installed. I have installed https://editpyxl.readthedocs.io/en/latest/

I placed a little script in the same directory as the PHP script, which I call with PHP:

from editpyxl import Workbook
import sys
import logging

logging.basicConfig()

if len(sys.argv) != 4:
    print("Three arguments accepted, got " + (str(len(sys.argv) -1)))
    print("Argument 1: Sheet name, Argument 2: Cell Identifier, Argument 3: New Value")
    sys.exit();

wb = Workbook()
source_filename = r'OriginalFile.xlsm'
wb.open(source_filename)
ws = wb[sys.argv[1]]
ws.cell(sys.argv[2]).value = sys.argv[3]
destination_filename = "NewFile.xlsm"
wb.save(destination_filename)
wb.close()

In PHP I call it via

exec('python excel.py "SheetName" "CellName" "NewValue"')

Seems to be a workaround but it works (especially on Linux) and is very easy to implement. This solution has a performance limitation though. The python script reads, changes the value and saves the excel in each runtime. If you only have some values to change, this might not be a problem but if you plan to edit larger Excel Files with a larger amount of cells to edit, you might write the complete code that edits the xlsm in python.

This code, however, works for me. It edits the Excel and all Formulars/Calculations inside stay fine, also the Macros are still untouched.

Niklas Riecken
  • 303
  • 1
  • 6
  • 20