各位前輩好
小弟我是初學Python的新手
目前正在嘗試做一些Python的應用希望能夠在工作上有些幫助
功能如下:
1.xlsx:為來源的excel檔案
例如表格欄位如下:
name number age
abc 1 11
def 2 12
ghi 3 13
jkl 4 14
mno 5 15
我這裡依據name這一列輸出檔案會變成
abc.xlsx
def.xlsx
ghi.xlsx
jkl.xlsx
mno.xlsx
每個檔案會別有name和number以及age這個欄位,下面並有該當的資料
以下是我的程式碼
import pandas as pd
# 設定輸入檔案路徑、讀取工作表名稱以及輸出檔案的路徑
import_file_path = 'D:/automatic/excel/a.xlsx'
excel_sheet_name = '工作表1'
export_file_path = 'D:/excelprocess'
# 定義df_order並透過pandas讀取指定的路徑且指定分頁的xlsx檔案
df_order = pd.read_excel(import_file_path, sheet_name=excel_sheet_name)
# 定義company_name為檔案中僅取出name那一列的資料
company_name = df_order['name'].unique()
# 依據name的欄位分割成不同顯示方式並輸出成Excel檔案
for i in company_name:
df_order_company = df_order[df_order['name'] == i]
df_order_company.to_excel(export_file_path+'/'+i+'xlsx')
程式碼的部分我想應該沒什麼問題(因為我是按照別人的範例依樣畫葫蘆)
但是在輸出的時候出現了error
內容如下
Traceback (most recent call last):
File "C:\Users\rucif\PycharmProjects\file\venv\lib\site-packages\pandas\io\excel\_base.py", line 999, in __new__
engine = config.get_option(f"io.excel.{ext}.writer", silent=True)
File "C:\Users\rucif\PycharmProjects\file\venv\lib\site-packages\pandas\_config\config.py", line 256, in __call__
return self.__func__(*args, **kwds)
File "C:\Users\rucif\PycharmProjects\file\venv\lib\site-packages\pandas\_config\config.py", line 128, in _get_option
key = _get_single_key(pat, silent)
File "C:\Users\rucif\PycharmProjects\file\venv\lib\site-packages\pandas\_config\config.py", line 114, in _get_single_key
raise OptionError(f"No such keys(s): {repr(pat)}")
pandas._config.config.OptionError: No such keys(s): 'io.excel..writer'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\rucif\PycharmProjects\file\file.py", line 18, in <module>
df_order_company.to_excel(export_file_path+'/'+i+'xlsx')
File "C:\Users\rucif\PycharmProjects\file\venv\lib\site-packages\pandas\core\generic.py", line 2345, in to_excel
formatter.write(
File "C:\Users\rucif\PycharmProjects\file\venv\lib\site-packages\pandas\io\formats\excel.py", line 888, in write
writer = ExcelWriter( # type: ignore[abstract]
File "C:\Users\rucif\PycharmProjects\file\venv\lib\site-packages\pandas\io\excel\_base.py", line 1003, in __new__
raise ValueError(f"No engine for filetype: '{ext}'") from err
ValueError: No engine for filetype: ''
Process finished with exit code 1
不知道這是哪裡出現問題了?還請前輩指教,謝謝
你的 for 迴圈第一行那樣寫就錯了,裡面判斷是 bool,一定錯
然後建議直接在讀取時直接加上 name,直接讀
df_order = pd.read_excel(import_file_path, sheet_name=excel_sheet_name, index_col='name')
df_order.loc['abc']
或是直接這樣子
df_order = pd.read_excel(import_file_path, sheet_name=excel_sheet_name)
print(df_order.loc[0])