使用Python的xlrd和xlutils保存Excel格式的问题

简而言之,我想将一个Excel文件的所有格式保存到另一个文件中。 但是,尽pipe使用了formatting_info=True标志,但格式只对所更改的行内的所有未更改的单元格显示。 有什么build议?

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

在这里input图像说明

在这里输入图像说明

在这里输入图像说明

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

解决方法是使用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") 

在使用openpyxl时,我遇到了类似的问题 – 由于某些原因,在可用的模块中这似乎不能很好地处理。 我input数据后,根据需要重新设置单元格,使用下面的语法:

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

关于使用xlrd实现这种types的语法的信息可以在这里find。