python - 使用 Python 的 xlrd 和 xlutils 保留 Excel 格式的问题

标签 python excel xlrd xlutils

<分区>

简而言之,我想将一个 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")

在此输入图片描述

enter image description here

enter image description here

最佳答案

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")

关于python - 使用 Python 的 xlrd 和 xlutils 保留 Excel 格式的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28240254/

相关文章:

Python比较两行不同的矩阵

python - 将字节串转换为字节或字节数组

python - django使用xlrd读取批量excel文件太慢

excel - 如何查找后期绑定(bind)引用的名称

python - xlrd 中的 col 输出似乎是 xf 格式文本。我该如何摆脱这个?

python - Xlrd、xlwt 和 xlutils : how do they work together

python - 分类特征留一法编码的Pandas实现

python - 如何在访问日志中添加 Flask 全局 'g' 对象的 id?

excel - 仅在导入新数据后,每个循环的对象需要错误

python - 在 Python 中使用 XLRD 迭代行和列