一、保持原excel样式,进行修改或追加内容

文章参考链接

import xlrd
import xlutils.copy


# 指定原始excel路径
filepath = 'test.xls'



# rb打开该excel,formatting_info=True表示打开excel时并保存原有的格式
rb = xlrd.open_workbook(filepath, formatting_info=True)

# 创建一个可写入的副本
wb = xlutils.copy.copy(rb)


# 本文重点,该函数中定义:对于没有任何修改的单元格,保持原有格式。 直接复制用
def setOutCell(outSheet, col, row, value):
    """ 更改单元格值而不更改格式. """

    def _getOutCell(outSheet, colIndex, rowIndex):
        """ hack:提取内部xlwt单元表示。"""
        row = outSheet._Worksheet__rows.get(rowIndex)
        if not row: return None

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

    # 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
# 写入excel数据
# outSheet = wb.get_sheet(0)  # 根据sheet的索引获取sheet对象,从0开始
outSheet = wb.get_sheet("押品页面展示(洋河)")  # 根据表名获取表对象
setOutCell(outSheet, 1, 11, "你好啊")  # 操作的sheet表, 列数,行数, 内容

wb.save('test.xls')
print('finish')

Categories: py之excel

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *