简而言之,我想将一个 Excel 文件的所有格式保留到另一个文件中。然而,尽管使用了 formatting_info=True
标志,但格式只会出现在已更改行中所有未更改的单元格中。有什么建议吗?
import xlrd, xlutils
from xlrd import open_workbook
from xlutils.copy import copy
inBook = xlrd.open_workbook(r"path/to/file/format_input.xls", formatting_info=True, on_demand=True)
outBook = xlutils.copy.copy(inBook)
outBook.get_sheet(0).write(0,0,'changed!')
outBook.save(r"path/to/file/format_output.xls")
在此输入图片描述
xlwt.write
接受样式信息作为它的第三个参数。不幸的是,xlrd 和 xlwt 使用两种截然不同的 XF 对象格式。所以不能直接将单元格的样式从xlrd
读取的工作簿复制到xlwt
创建的工作簿。
解决方法是使用xlutils.XLWTWriter
复制文件,然后取回that 对象的样式信息以保存单元格的样式更新。
首先,您需要 John Machin 在 a very similar question 中提供的 patch 功能:
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")