1

我正在使用 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')
4

2 回答 2

1

使用这些包,没有办法避免丢失评论和图表,以及许多其他工作簿功能。包xlrd根本不读取它们,xlwt包根本不写它们。xlutils只是其他两个包之间的桥梁;它不能读任何不能读xlrd的东西,它不能写任何不能写的东西xlwt

为了实现您想要实现的目标,您最好的选择可能是自动化正在运行的 Excel 实例;最好的 Python 包是xlwings,它适用于 Windows 或 Mac。

于 2016-10-03T21:13:44.150 回答
0

你能用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
于 2016-10-03T21:13:08.193 回答