【问题标题】:Issues in preserving Excel formatting with Python's xlrd and xlutils [duplicate]使用 Python 的 xlrd 和 xlutils 保留 Excel 格式的问题 [重复]
【发布时间】:2015-01-30 16:24:54
【问题描述】:

简单地说,我想将一个 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")

在此处输入图片说明

【问题讨论】:

    标签: python excel xlrd xlutils


    【解决方案1】:

    xlwt.write 接受样式信息作为其第三个参数。不幸的是,xlrd 和 xlwt 使用两种截然不同的 XF 对象格式。所以不能直接将xlrd读取的工作簿中的单元格样式复制到xlwt创建的工作簿中。

    解决方法是使用xlutils.XLWTWriter复制文件,然后取回那个对象的样式信息来保存你要更新的单元格的样式。

    首先你需要由 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")
    

    【讨论】:

    • Sylvain Leroux - 抱歉回复晚了。这正是我所需要的。谢谢!
    【解决方案2】:

    我在使用 openpyxl 时遇到了类似的问题 - 出于某种原因,这似乎在可用模块中处理得不是很好。在输入数据后,我最终只是根据需要重新设置单元格的样式,使用以下语法:

    #Formatting
    from openpyxl.styles import Style, Color, PatternFill, Alignment, Font, NumberFormat
    #Allows for conditional formatting
    from openpyxl.formatting import CellIsRule #Allows for Conditional Formatting
    
    for cell in changed_cells:
        cell.style = Style(fill=PatternFill(patternType='solid', fgColor=Color('FFff8888')), 
                             font=Font(name="Arial",size=11), 
                             alignment=Alignment(horizontal="center"))
    

    可以在here找到使用xlrd实现这种东西的语法信息。

    【讨论】:

    • 感谢 Alecg_O 的帮助。我很高兴您指出了重新格式化单元格的方法。我会牢记这一点,但 Sylvain Leroux 提供了一个无需重新格式化的解决方案——这正是我所寻找的。再次感谢!
    猜你喜欢
    • 1970-01-01
    • 2017-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-09
    • 1970-01-01
    相关资源
    最近更新 更多