使用 pandas 读取和更新 XLSM 文件中的工作表,同时保留 VBA 代码

Hyv*_*vrt 7 python excel vba pandas

我需要读取 xlsm 文件并更新文件中的一些工作表。我想用 pandas 来达到这个目的。

我尝试了以下帖子中提供的答案。当我重新添加 VBA 项目时,我看不到 VBA 宏。
https://stackoverflow.com/posts/28170939/revisions

这是我尝试过的步骤,

从原始.xlsm文件中提取VBA_project.bin,然后

writer = pd.ExcelWriter('original.xlsx', engine='xlsxwriter')
workbook = writer.book
workbook.filename = 'test.xlsm'
workbook.add_vba_project('vbaProject.bin')
writer.save()
Run Code Online (Sandbox Code Playgroud)

这样,我看不到附加到“test.xlsm”的 VBA 宏。即使我将其写入“original.xlsm”文件,结果也是相同的。

如何保留 VBA 宏或将它们添加回原始 xlsm 文件?

另外,有没有办法可以打开“xlsm”文件本身而不是使用“xlsx”对应文件pd.ExcelWriter

小智 7

你可以用 pandas 轻松做到这一点

import pandas as pd
import xlrd

# YOU MUST PUT sheet_name=None TO READ ALL SHEETS IN YOUR XLSM FILE
df = pd.read_excel('YourFile.xlsm', sheet_name=None)

# prints all sheets
print(df)
Run Code Online (Sandbox Code Playgroud)


ASH*_*ASH 1

啊,我明白了。我仍然不知道你在做什么,但这里有一些让 Python 与 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=win32com.client.Dispatch("Excel.Application")  
xl.Workbooks.Open(Filename="C:\your_path\excelsheet.xlsm") #opens workbook in readonly mode. 

#Run Macro
xl.Application.Run("excelsheet.xlsm!modulename.macroname") 

#Save Document and Quit.
xl.Application.Save()
xl.Application.Quit() 

#Cleanup the com reference. 
del xl
Run Code Online (Sandbox Code Playgroud)
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)


workbook.close()
Run Code Online (Sandbox Code Playgroud)
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
wb.save("C:\\your_path\\sample.xlsx")
Run Code Online (Sandbox Code Playgroud)