Python——excel追加写入数据

方法一:
适用于xls文件,会对文件进行copy操作。能保留大部分文件原格式,但批注会丢失

import xlrd

# excel追加写入(xls:批注会丢失)
def write_excel_xls_append(file_path, df):  # df:DataFrame
    book = xlrd.open_workbook(file_path, formatting_info=True)  # 保持Excel原格式;type:book
    workbook = copy(book)  # type:workbook
    worksheet = workbook.get_sheet(0)  # == workbook.sheets[0];type:worksheet
    for i in range(0, len(df)):  # 行
        for j in range(13):  # 列
            worksheet.write(i + 2, j, str(df.iloc[i][j]))  # 追加数据,从3行开始写入
    workbook.save(file_path)

方法二:
只适用于xlsx文件,不适用xls文件,不存在copy的过程。能保留文件原格式,包括批注。

from openpyxl import load_workbook

# excel追加写入(xlsx:批注不会丢失)
def write_excel_xlsx_append(file_path, df):  # df:DataFrame
    wb = load_workbook(file_path)  # type:workbook
    ws = wb.active  # type:worksheet
    for i in range(0, len(df)):  # 行
        for j, c in enumerate("ABCDEFGHIJKLM"):  # 列
            ws[f"{c}{i + 3}"] = str(df.iloc[i][j])  # 追加数据,从3行开始写入
    wb.save(file_path)

你可能感兴趣的:(Python系列)