1. 程式人生 > >pandas分別寫入excel的不同sheet

pandas分別寫入excel的不同sheet

pandas可以非常方便的寫資料到excel,那麼如何寫多個dataframe到不同的sheet呢?
使用pandas.ExcelWriter

import pandas as pd

writer = pd.ExcelFile('your_path.xlsx')

df1 = pd.DataFrame()
df2 = pd.DataFrame()

df1.to_excel(writer, sheet_name='df_1')
df2.to_excel(writer, sheet_name='df_2')

writer.save()

網上的大部分答案基本上都是這些內容,但是這裡有個大坑,你會發現找不到想要的xlsx檔案。
那麼問題出在哪?
我們看看ExcelWriter原始碼就知道了

class ExcelFile(object):
    """
    Class for parsing tabular excel sheets into DataFrame objects.
    Uses xlrd. See read_excel for more documentation

    Parameters
    ----------
    io : string, path object (pathlib.Path or py._path.local.LocalPath),
        file-like object or xlrd workbook
        If a string or path object, expected to be a path to xls or xlsx file
    engine: string, default None
        If io is not a buffer or path, this must be set to identify io.
        Acceptable values are None or xlrd
    """

這裡已經說的很清楚了,希望傳入的是excel的路徑,你只傳了個檔名,當然找不到了。
而且從這裡我們可以看到,pandas.ExcelWriter實質上是用xlrd來解析excel的。這個wrapper提供了更簡單的介面。