[英]Python writing (xlwt) to an existing Excel Sheet, drops charts and formatting
我正在使用 python 來自動化一些任務並最終寫入現有的電子表格。 我正在使用 xlwt、xlrd 和 xlutils 模塊。
所以我設置它的方法是打開文件,制作一個副本,寫入它,然后將它保存回同一個文件。 當我執行最后一步時,所有 excel 格式(例如注釋和圖表)都將被刪除。 有沒有辦法解決這個問題? 我認為這與excel對象有關。
謝謝
示例代碼
import xlwt
import os
import xlrd, xlutils
from xlrd import open_workbook
from xlutils.copy import copy
style1 = xlwt.easyxf('font: name Calibri, color-index black, bold off; alignment : horizontal center', num_format_str ='###0')
script_dir = os.path.dirname('_file_')
Scn1 = os.path.join(script_dir, "\sample\Outlet.OUT")
WSM_1V = []
infile = open (Scn1, "r")
for line in infile.readlines():
WSM_1V.append(line [-10:-1])
infile.close()
Existing_xls = xlrd.open_workbook(r'\test\test2.xls', formatting_info=True, on_demand=True)
wb = xlutils.copy.copy(Existing_xls)
ws = wb.get_sheet(10)
for i,e in enumerate(WSM_1V,1):
ws.write (i,0, float(e),style1)
wb.save('test2.xls')
使用這些包,無法避免丟失注釋和圖表以及許多其他工作簿功能。 xlrd
包根本不讀取它們,而xlwt
包根本不寫入它們。 xlutils
只是其他兩個包之間的橋梁; 它無法讀取xlrd
無法讀取的任何內容,也無法寫入xlwt
無法寫入的任何內容。
要實現您想要實現的目標,最好的選擇可能是自動運行 Excel 實例; 最好的 Python 包是xlwings ,它適用於 Windows 或 Mac。
你能用 win32com 做到這一點嗎?
from win32com import client
...
xl = client.Dispatch("Excel.Application")
wb = xl.Workbooks.Open(r'\test\test2.xls')
ws = wb.Worksheets[10]
for i,e in enumerate(WSM_1V,1):
ws.Cells[i][0].Value = float(e)
wb.save
wb.Close()
xl.Quit()
xl = None
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.