由於您的CSV導入到電子表格可以使用Excel VBA宏使用QueryTables考慮有Python的複製VBA與COM接口,Excel對象庫來處理。之前的所有宏代碼保持不變,因爲沒有被覆蓋,但是單元數據。 注意:下面假定您正在使用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
開始錄製宏,而這樣做你列出的操作。然後拿出它的結果代碼並進行處理。 – user3598756
基本上,我從你的問題中瞭解到,你想在數據框中將列B中的值替換爲Q? 如果是這種情況,那麼您可以使用'df.drop()'並通過'df [] = ' –
@ user3598756添加新列謝謝您的評論。但是,我不是一個非常精明的人,所以我不完全理解你的建議。似乎您建議手動處理複製和粘貼數據。雖然我試圖自動化我的編譯工作。儘管如此,謝謝你的建議! – arnold