xlwt.write
接受样式信息作为它的第三个参数。不幸的是,xlrd 和 xlwt 使用两种截然不同的 XF 对象格式。因此,您不能直接将单元格的样式从读取的工作簿复制xlrd
到创建的工作簿中xlwt
。
解决方法是使用xlutils.XLWTWriter
复制文件,然后取回该对象的样式信息以保存您将更新的单元格的样式。
首先,您需要John Machin 在一个非常相似的问题中提供的补丁功能:
from xlutils.filter import process,XLRDReader,XLWTWriter
#
# suggested patch by John Machin
# https://stackoverflow.com/a/5285650/2363712
#
def copy2(wb):
w = XLWTWriter()
process(
XLRDReader(wb,'unknown.xls'),
w
)
return w.output[0][1], w.style_list
然后在你的主要代码中:
import xlrd, xlutils
from xlrd import open_workbook
from xlutils.copy import copy
inBook = xlrd.open_workbook(r"/tmp/format_input.xls", formatting_info=True, on_demand=True)
inSheet = inBook.sheet_by_index(0)
# Copy the workbook, and get back the style
# information in the `xlwt` format
outBook, outStyle = copy2(inBook)
# Get the style of _the_ cell:
xf_index = inSheet.cell_xf_index(0, 0)
saved_style = outStyle[xf_index]
# Update the cell, using the saved style as third argument of `write`:
outBook.get_sheet(0).write(0,0,'changed!', saved_style)
outBook.save(r"/tmp/format_output.xls")