如何让Pandas创建新表而不是覆盖?

时间:2017-06-14 17:49:44

标签: python excel pandas

我正在为我的工作构建一个小型自动报告工具。我试图让我的代码工作,每次(每天)创建另一张表,我运行程序并生成报告。

date_time = time.strftime('%b %d %Y')

writer = pd.ExcelWriter('BrokerRisk.xlsx', engine='xlsxwriter')
df.to_excel(writer,'DataFrame-' + date_time)
sums.to_excel(writer,'TotalByCounterparty-' + date_time)
sums_sort.to_excel(writer,'SortedRank-' + date_time)

workbook  = writer.book
worksheet1 = writer.sheets['DataFrame-' + date_time]
worksheet2 = writer.sheets['TotalByCounterparty-' + date_time]
worksheet3 = writer.sheets['SortedRank-' + date_time]
writer.save()

我尝试实现日期功能,以便每天在技术上更改名称,但这似乎也不起作用。任何人都可以建议一个简单的修

1 个答案:

答案 0 :(得分:1)

engine=openpyxl用作writer可以执行您想要的操作,例如:

from openpyxl import load_workbook
from copy import copy
import time

class CopyWorkbook(object):
    def __init__(self, fname):
        self.fname = fname
        self.wb = load_workbook(fname)

    def save(self):
        self.wb.save(self.fname)

    def copy_worksheet(self, from_worksheet):
        # Create new empty sheet and append it to self(Workbook)
        ws = self.wb.create_sheet( title=from_worksheet.title )

        for row, row_data in enumerate(from_worksheet.rows,1):
            for column, from_cell in enumerate(row_data,1):
                cell = ws.cell(row=row, column=column)
                cell.value = from_cell.value
                cell.font = copy(from_cell.font)

date_time = time.strftime('%b %d %Y')
writer = pd.ExcelWriter('dummy.xlsx', engine='openpyxl')
df.to_excel(writer,'DataFrame-' + date_time)
# ... Other DataFrame's .to_excel(writer, ...

wb = CopyWorkbook('BrokerRisk.xlsx')
for ws_new in writer.book.worksheets:
    wb.copy_worksheet(ws_new)

wb.save()

使用Python测试:3.4.2 - openpyxl:2.4.1 - LibreOffice:4.3.3.2