Home » excel » python – Reading and updating sheets in an XLSM file using pandas while preserving the VBA macros

python – Reading and updating sheets in an XLSM file using pandas while preserving the VBA macros

Posted by: admin April 23, 2020 Leave a comment


I have a requirement to read an xlsm file with VBA macros and update some of the sheets in the file. I want to use pandas for this purpose and trying to understand how this can be done.

I tried answers presented in the following post, however, I couldn’t see the VBA macros getting preserved when I add the VBA project back.


Here are the steps I tried,

Extracted the vba_project.bin out of the original.xlsm file and then

writer = pd.ExcelWriter('original.xlsx', engine='xlsxwriter')
workbook = writer.book
workbook.filename = 'test.xlsm'

with this I don’t see the VBA macros getting attached to “test.xlsm”. The result is the same even if I write it to the “original.xlsm” file.

Any thoughts on how to preserve the VBA macros or add back them to the original xlsm file?

ALso, is there a way I can open the ‘xlsm’ file itself rather than the “xlsx” counter part using pd.ExcelWriter

Thanks in advance.

How to&Answers:

Ah, I see. I still can’t tell what you are doing, but here are a few general samples of code to get Python to communicate with Excel.

Read contents of a worksheet in Excel:

import pandas as pd
from pandas import ExcelWriter
from pandas import ExcelFile

df = pd.read_excel('C:\your_path\test.xls', sheetname='Sheet1')


Use Python to run Macros in Excel:
import os
import win32com.client

#Launch Excel and Open Wrkbook
xl.Workbooks.Open(Filename="C:\your_path\excelsheet.xlsm") #opens workbook in readonly mode. 

#Run Macro

#Save Document and Quit.

#Cleanup the com reference. 
del xl

Write, from Python, to Excel:

import xlsxwriter

# Create an new Excel file and add a worksheet.
workbook = xlsxwriter.Workbook('C:/your_path/ranges_and_offsets.xlsx')
worksheet = workbook.add_worksheet()

# Widen the first column to make the text clearer.
worksheet.set_column('A:A', 20)

# Add a bold format to use to highlight cells.
bold = workbook.add_format({'bold': True})

# Write some simple text.
worksheet.write('A1', 'Hello')

# Text with formatting.
worksheet.write('A2', 'World', bold)

# Write some numbers, with row/column notation.
worksheet.write(2, 0, 123)
worksheet.write(3, 0, 123.456)


from openpyxl import Workbook
wb = Workbook()

# grab the active worksheet
ws = wb.active

# Data can be assigned directly to cells
ws['A1'] = 42

# Rows can also be appended
ws.append([1, 2, 3])

# Python types will automatically be converted
import datetime
ws['A2'] = datetime.datetime.now()

# Save the file