Python Pandas - 將資料寫入 Excel 檔案



Pandas 是 Python 中的一個數據分析庫,廣泛用於處理來自各種格式的結構化資料,包括 CSV、SQL 和 Excel 檔案。該庫的一個關鍵特性是您可以使用to_excel()方法輕鬆地將資料從 Pandas DataFrame 和 Series 直接匯出到 Excel 電子表格中。

Pandas 中的to_excel()方法允許您將 DataFrame 或 Series 中的資料匯出到 Excel 檔案。此方法提供了指定各種引數的靈活性,例如檔案路徑、工作表名稱、格式選項等等。

在本教程中,我們將學習如何使用pandas.to_excel()方法將 Pandas 物件中的資料寫入 Excel 檔案。

將單個 DataFrame 寫入 Excel

只需呼叫帶有 Excel 檔名和可選工作表名的DataFrame.to_excel()方法,即可直接將 Pandas DataFrame 物件的內容匯出到 Excel 檔案的工作表中。

示例

以下是如何使用DataFrame.to_excel()方法將 Pandas DataFrame 的內容寫入 Excel 檔案的基本示例。

import pandas as pd

# Create a DataFrame
df = pd.DataFrame([[5, 2], [4, 1]],index=["One", "Two"],columns=["Rank", "Subjects"])

# Display the DataFrame
print("DataFrame:\n", df)

# Export DataFrame to Excel
df.to_excel('Basic_example_output.xlsx')

print('The Basic_example_output.xlsx file is saved successfully..')

以下是上述程式碼的輸出:

DataFrame:
Rank Subjects
One 5 2
Two 4 1
The Basic_example_output.xlsx file is saved successfully..

注意:執行每個程式碼後,您可以在工作目錄中找到建立的輸出檔案。

將多個 DataFrame 寫入不同的工作表

可以使用ExcelWriter類將多個 DataFrame 寫入同一個 Excel 檔案中的不同工作表。

示例

以下是如何使用ExcelWriter類和df.to_excel()方法將多個 DataFrame 寫入同一個 Excel 檔案中不同工作表的示例。

import pandas as pd

df1 = pd.DataFrame(
   [[5, 2], [4, 1]],
   index=["One", "Two"],
   columns=["Rank", "Subjects"]
)

df2 = pd.DataFrame(
   [[15, 21], [41, 11]],
   index=["One", "Two"],
   columns=["Rank", "Subjects"]
)

print("DataFrame 1:\n", df1)
print("DataFrame 2:\n", df2)

with pd.ExcelWriter('output_multiple_sheets.xlsx') as writer:
	df1.to_excel(writer, sheet_name='Sheet_name_1')
	df2.to_excel(writer, sheet_name='Sheet_name_2')

print('The output_multiple_sheets.xlsx file is saved successfully..')

以下是上述程式碼的輸出:

DataFrame 1:
Rank Subjects
One 5 2
Two 4 1
DataFrame 2:
Rank Subjects
One 15 21
Two 41 11
The output_multiple_sheets.xlsx file is saved successfully..

將資料追加到現有的 Excel 檔案

可以使用ExcelWritermode='a'將 DataFrame 的內容追加到現有的 Excel 檔案中。

示例

以下示例演示如何將 DataFrame 的內容追加到現有的 Excel 檔案。

import pandas as pd

# Create a new DataFrame
data3 = {
    'Rank': [7, 8, 9],
    'Subjects': ['Music', 'Art', 'Literature']
}
df3 = pd.DataFrame([[51, 11], [21, 38]],index=["One", "Two"],columns=["Rank", "Subjects"])

# Append the DataFrame to an existing Excel file
with pd.ExcelWriter('output_multiple_sheets.xlsm', mode='a') as writer:
    df3.to_excel(writer, sheet_name='Sheet_name_3', index=False)

print('The output_multiple_sheets.xlsm file is saved successfully with the appended sheet..')

以下是上述程式碼的輸出:

The output_multiple_sheets.xlsm file is saved successfully with the appended sheet..

將 Excel 檔案寫入記憶體

可以透過使用BytesIOStringIO以及ExcelWriter將 Excel 檔案寫入記憶體(類似緩衝區的物件),而不是將其儲存到磁碟。

示例

以下示例演示如何使用BytesIOExcelWriter類將 Excel 檔案寫入記憶體物件。

import pandas as pd
from io import BytesIO

df = pd.DataFrame(
   [[5, 2], [4, 1]],
   index=["One", "Two"],
   columns=["Rank", "Subjects"]
)

print("DataFrame :\n", df)

# Create a BytesIO object
bio = BytesIO()

# Write the DataFrame to the BytesIO buffer
with pd.ExcelWriter(bio, engine='xlsxwriter') as writer:
    df.to_excel(writer, sheet_name='Sheet1')

# Get the Excel file from memory
bio.seek(0)
excel_data = bio.read()

print('The Excel file is save in Memory successfully..')

以下是上述程式碼的輸出:

DataFrame :
Rank Subjects
One 5 2
Two 4 1
The Excel file is save in Memory successfully..

選擇 Excel Writer 引擎

Pandas 支援多個用於寫入 Excel 檔案的引擎,例如openpyxlxlsxwriter。您可以根據需要使用DataFrame.to_excel()方法的engine引數顯式指定引擎。並確保您已在系統中安裝了所需的引擎。

示例

此示例演示使用DataFrame.to_excel()方法的engine引數儲存具有指定引擎的 Excel 檔案。

import pandas as pd
from io import BytesIO

df = pd.DataFrame(
   [[5, 2], [4, 1]],
   index=["One", "Two"],
   columns=["Rank", "Subjects"]
)

# Write DataFrame using xlsxwriter engine
df.to_excel('output_xlsxwriter.xlsx', sheet_name='Sheet1', engine='xlsxwriter')

print('The output_xlsxwriter.xlsx is saved successfully..')

以下是上述程式碼的輸出:

The output_xlsxwriter.xlsx is saved successfully..
廣告