# Python:將 list 資料寫入 Excel 多個不同分頁
**[Python]Use pandas DataFrame & to_excel write into multiple sheets and export excel file**
<br/>
如果還沒安裝過pandas,需要先打開執行CMD.exe,安裝pandas套件指令:
```python=
#Command Line
python -m pip install pandas
```
Pandas套件裡常用的有read_excel(讀取excel檔案)以及to_excel(寫入檔案)
## **〔Basic Usage|標準語法〕**
```python=
df.to_excel(writer, sheet_name='Sheet1', header=True, index=True, engine=None)
```
## **〔Sample Code|範例語法〕**
```python=
import pandas as pd
output_list_1 = [['這是','第一','分頁'] , ['AAA','BBB','CCC']]
output_list_2 = [['這是','第二','分頁'] , ['aaa','bbb','ccc']]
# 想匯出的檔案名稱
writer = pd.ExcelWriter("output_file.xls")
# 輸出檔案中每頁欄位的標題
excel_header = ['欄位A','欄位B','欄位C']
# 把list型態資料放入DataFrame當中,再寫入output_file.xls
df1 = pd.DataFrame(output_list_1)
df1.to_excel(writer,sheet_name = "工作簿_分頁1", header = excel_header, index = False)
df2 = pd.DataFrame(output_list_2)
df2.to_excel(writer,sheet_name = "工作簿_分頁2", header = excel_header, index = False)
writer.close()
```
## **〔Parameters|自訂參數〕**
sheet_name:可以自訂每頁工作簿名稱
header:是檔案上側第一行欄位內文,預設是[0, 1, 2......]
index:預設是True,會在左側的第一列有索引值,預設也是[0, 1, 2......]
engine:常用的有 ‘openpyxl’ 跟 ‘xlsxwriter’
## **〔Output Demo|檔案輸出〕**
![](https://i.imgur.com/R5de90h.png)
<br/>
**〔Reference〕**
https://docs.python.org/3/installing/
https://pandas.pydata.org/docs/reference/api/pandas.read_excel.html
https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_excel.html
---
: : 20210414 : : 與松 withhhsong : :
###### tags: `python` `tutorials` `withhhsong`