由于您可以使用QueryTables 使用 Excel VBA 宏处理将 csv 导入电子表格,因此请考虑让 Python 使用 Excel 对象库的 COM 接口复制 VBA。所有以前的宏代码都保持不变,因为除了单元格数据之外什么都没有被覆盖。 注意:以下假设您使用的是 Excel for Windows。
使用win32com 库,Python 几乎可以复制 VBA 所做的任何事情。事实上,您会知道 VBA 是 Office 应用程序中的附加引用,而不是本机的内置对象,并且执行相同的 COM 接口!在您的 IDE 中查看 Tools\References 中的第一个选定项目。
import pandas as pd
import win32com.client as win32
# ...same pandas code...
macrofile = "C:\\Path\\To\\Macro\\Workbook.xlsm"
strfile = "C:\\Path\\To\\CSV\\Output.csv"
df.to_csv(strfile)
try:
xl = win32.gencache.EnsureDispatch('Excel.Application')
wb = xl.Workbooks.Open(macrofile)
# DELETE PREVIOUS DATA
wb.Sheets("Source").Range("B:Q").EntireColumn.Delete()
# ADD QUERYTABLE (SPECIFYING DESTINATION CELL START)
qt = wb.Sheets("Source").QueryTables.Add(Connection="TEXT;" + strfile,
Destination=wb.Sheets(1).Cells(2, 2))
qt.TextFileParseType = 1
qt.TextFileConsecutiveDelimiter = False
qt.TextFileTabDelimiter = False
qt.TextFileSemicolonDelimiter = False
qt.TextFileCommaDelimiter = True
qt.TextFileSpaceDelimiter = False
qt.Refresh(BackgroundQuery=False)
# REMOVE QUERYTABLE
for qt in wb.Sheets("Source").QueryTables:
qt.Delete()
# CLOSES WORKBOOK AND SAVES CHANGES
wb.Close(True)
except Exception as e:
print(e)
finally:
qt = None
wb = None
xl = None
或者,在 VBA 中创建一个新宏(放置在独立模块中)并让 Python 调用它,将 csv 文件路径作为参数传递:
VBA
Public Sub ImportCSV(strfile As String)
Dim qt As QueryTable
ThisWorkbook.Sheets("Source").Range("B:Q").EntireColumn.Delete
' ADD QUERYTABLE
With ThisWorkbook.Sheets("Source").QueryTables.Add(Connection:="TEXT;" & strfile, _
Destination:=ThisWorkbook.Sheets(1).Cells(2, 2))
.TextFileParseType = xlDelimited
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.Refresh BackgroundQuery:=False
End With
' REMOVE QUERYTABLE
For Each qt In ThisWorkbook.Sheets(1).QueryTables
qt.Delete
Next qt
Set qt = Nothing
End Sub
Python
import pandas as pd
import win32com.client as win32
# ...same pandas code...
macrofile = "C:\\Path\\To\\Macro\\Workbook.xlsm"
strfile = "C:\\Path\\To\\CSV\\Output.csv"
df.to_csv(strfile)
try:
xl = win32.gencache.EnsureDispatch('Excel.Application')
wb = xl.Workbooks.Open(macrofile)
xl.Application.Run('ImportCSV', strfile)
wb.Close(True)
xl.Quit
except Exception as e:
print(e)
finally:
wb = None
xl = None