这有两个部分。

首先,您必须在打开源工作簿时启用格式化信息的读取。然后复制操作将复制格式化。

import xlrd

import xlutils.copy

inBook = xlrd.open_workbook('input.xls', formatting_info=True)

outBook = xlutils.copy.copy(inBook)

其次,您必须处理更改单元格值重置该单元格的格式的事实。

这不太漂亮;我使用以下hack,其中我手动复制格式索引(xf_idx):

def _getOutCell(outSheet, colIndex, rowIndex):

""" HACK: Extract the internal xlwt cell representation. """

row = outSheet._Worksheet__rows.get(rowIndex)

if not row: return None

cell = row._Row__cells.get(colIndex)

return cell

def setOutCell(outSheet, col, row, value):

""" Change cell value without changing formatting. """

# HACK to retain cell style.

previousCell = _getOutCell(outSheet, col, row)

# END HACK, PART I

outSheet.write(row, col, value)

# HACK, PART II

if previousCell:

newCell = _getOutCell(outSheet, col, row)

if newCell:

newCell.xf_idx = previousCell.xf_idx

# END HACK

outSheet = outBook.get_sheet(0)

setOutCell(outSheet, 5, 5, 'Test')

outBook.save('output.xls')

这保留几乎所有的格式。单元格注释不会被复制。

Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐