Search code examples
python-3.xexcelxlsm

How to add data into an existing xlsm file using editpyxl?


I am trying to add data to one cell in an existing xlsm file and then save it as a new xlsm file using editpyxl, but get an error stating the cell does not exist (IndexError: Cell A1 on TestSheet1 does not exist). There isn't much documentation on the editpyxl site but the one code example provided shows how to edit a workbook. Here is what I have (which is basically the same as the website example):

from editpyxl import Workbook

wb = Workbook()
wb.open('C:/Test/original.xlsm')
ws = wb['TestSheet1']
print(wb.sheetnames)
ws.cell('A1').value = 'abc123'
wb.save('C:/Test/newfile.xlsm')

Here is the full error:

Excel file does not contain xl/sharedStrings.xml
['TestSheet1', 'TestSheet2', 'TestSheet3']
Traceback (most recent call last):
  File "C:\Test\editxlsm-ep.py", line 7, in <module>
    ws.cell('A1').value = 'abc123'
  File "C:\Users\xxxxxx\AppData\Local\Programs\Python\Python38\lib\site- 
    packages\editpyxl\worksheet.py", line 64, in cell
    raise IndexError('Cell {0} on {1} does not exist'.format(coordinate, self.name))
IndexError: Cell A1 on TestSheet1 does not exist

I've tried it with an xlsx file just to see if the xlsm was perhaps the problem, but received the same error message. I also added the print line just to make sure it could load the file correctly. It appears that it does as the three sheet names are printed before the error occurs. I've searched for more help with the editpyxl library but haven't been able to find much. Versions of what I am using: Excel - 2016, editpyxl - 0.1.9, python - 3.8.1. Thanks.


Solution

  • So I was able to figure out why editpyxl was giving the error that the cell does not exist. As long as the cell contains no data, I get the error. Once I added some other data into 'A1' (I just added an 'x'), then it runs without error and the 'x' is replaced with the value I wanted. All of my macros and command buttons remain intact in the new xlsm file as well.