说明

由于默认xlwt包在写入excel时会初始化excel的样式,导致与预期不一致,通过以下方法能够保证原excel的基础样式写入

package

需要三个库:

  1. xlrd
  2. xlwt
  3. xlutils

写入方法

编写方法函数

def _getOutCell(sheet, colIndex, rowIndex):
    row = sheet._Worksheet__rows.get(rowIndex)
    if not row: return None

    cell = row._Row__cells.get(colIndex)
    return cell

def setOutCell(sheet, col, row, value, data_style=None):
    previousCell = _getOutCell(sheet, col, row)

    if data_style:
        sheet.write(row, col, value, data_style)
    else:
        sheet.write(row, col, value)
    
    if previousCell:
        newCell = _getOutCell(sheet, col, row)
        if newCell: newCell.xf_idx = previousCell.xf_idx

调用示例

from xlutils.copy import copy
import xlrd
import xlwt

sink_templete = xlrd.open_workbook(path, formatting_info=True)
workbook = copy(sink_templete)

sheet = workbook.get_sheet(0)
setOutCell(sheet, 1, 1, 'test')

workbook.save(new_path)