如何将一些数据附加到现有的xlsx工作表中?

时间:2018-02-05 11:29:29

标签: python python-3.x xlsx read-write

我想将我的数据库信息存储到 xlsx 文件中。我使用python创建了以下程序。

import xlsxwriter

def create_xlsx_file():
    workbook = xlsxwriter.Workbook('/home/script/report.xlsx')
    worksheet = workbook.add_worksheet()

    data = ['DataBase Name', 'Total Images', 'Gallary Name', 'Subject Name']

    r = 0
    c = 0
    for i in data:
        worksheet.set_column(c,c, 20)
        bold = workbook.add_format({'bold': True})
        worksheet.write(r, c, i)
        c = c + 1

    workbook.close()

def add_info_into_file(DataBase_Name, Total_Images, Gallary_Name, Subject_Name):
    workbook = xlsxwriter.Workbook('/home/script/report.xlsx')
    worksheet = workbook.add_worksheet()

    data = [DataBase_Name, Total_Images, Gallary_Name, Subject_Name]

    r = 2
    c = 0
    for i in data:
        worksheet.set_column(c,c, 20)
        bold = workbook.add_format({'bold': True})
        worksheet.write(r, c, i)
        c = c + 1

    workbook.close()

create_xlsx_file()
add_info_into_file("msc", 100, "Mat", "rsp")

在上面的程序中,如果我调用add_info_into_file()函数,则会截断现有数据。那么,如何将一些数据附加到现有的工作表中呢?

请有人帮助我。提前谢谢。

1 个答案:

答案 0 :(得分:3)

XlsxWriter仅作为文件编写者设计。它无法读取或修改现有的Excel文件。

您可以使用openpyxl进行文件追加。

#!/usr/bin/python3

from openpyxl import Workbook

book = Workbook()
sheet = book.active

rows = (
    (88, 46, 57),
    (89, 38, 12),
    (23, 59, 78),
    (56, 21, 98),
    (24, 18, 43),
    (34, 15, 67)
)

for row in rows:
    sheet.append(row)

book.save('appending.xlsx')