熊猫:保存数据框以打开工作簿

时间:2015-05-18 03:28:35

标签: python pandas xlsxwriter

我有一个打开的工作簿,可以写入数据。如何添加工作表来编写数据框的内容?

import xlsxwriter
import pandas as pd

workbook = xlsxwriter.Workbook('test.xlsx')
sheet1 = workbook.add_worksheet(name='sheet1')
sheet1.write(0, 0, 'test')
df = pd.DataFrame({'a': [1, 2, 3, 4], 'b': ['aa', 'bb', 'cc', 'dd']})
# write df somehow to next sheet. I usually use df.to_excel(filename, engine='xlsxwriter'), but this will create a new file
workbook.close()

1 个答案:

答案 0 :(得分:2)

正如您在评论中指出的那样,您无法将XlsxWriter工作簿对象传递给pandas to_excel()

作为一种解决方法,您可以使用空数据框创建工作表,然后访问下面的XlsxWriter工作簿和工作表对象。然后,您可以通过pandas界面添加额外的工作表。

以下是基于您的代码的小型工作示例:

import pandas as pd

# Create an pandas excel writer based on xlsxwriter.
writer = pd.ExcelWriter('test.xlsx', engine='xlsxwriter')

# Create a worksheet with an empty dataframe so the sheet is empty.
df = pd.DataFrame()
df.to_excel(writer, sheet_name='Sheet1')

# Access the underlying xlsxwriter worksheet and write to it.
workbook  = writer.book
worksheet = writer.sheets['Sheet1']
worksheet.write(0, 0, 'test')

# Create another dataframe with data.
df = pd.DataFrame({'a': [1, 2, 3, 4],
                   'b': ['aa', 'bb', 'cc', 'dd']})

# Write the dataframe to another worksheet.
df.to_excel(writer, sheet_name='Sheet2')

writer.save()

另见Working with Python Pandas and XlsxWriter