Skip to content
Advertisement

Python pandas write resulted dataframe to xlsm without losing the macro

I have a lot of excel files that I need to compile into a single excel file, and then copy the compiled one into an existing excel file (with macro / .xlsm) in a certain sheet.

I solved the first problem (compiling multiple excel files into a single excel file). The resulted dataframe is saved in .csv format. The resulted file looks like this. the resulted dataframe

Until here there is no issue. The next step that I am struggling to find out how to do it.

From the resulted dataframe I want to “copy-and-paste” the dataframe to the existing excel file with macro (.xlsm) in the sheet “Source” at the corresponding headers. The existing excel file looks like this. target excel file

As you may see from the picture above, I want to skip writing any data in the column A since the cells within this column is full of formula. I want to write the resulted dataframe in the column B to column Q within the existing excel file. However, before writing the data, I want delete all the existing data in all cells (except in the cells within column A).

So basically I want to do the following:

  1. delete all the values in the cells in the column B to column Q in the existing xlsm file (in the sheet “Source”)
  2. write the new values from the resulted dataframe to column B until column Q
  3. save the excel file back with the same name without losing the macro

Any feedback will be much appreciated! Thanks!

Regards,

Arnold

Advertisement

Answer

Sorry a bit late to come back updating my question. Finally I have solved my problem with openpyxl package.

So here is my final code:

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement