pandas 讀寫(xiě) Excel绣否,可以用于將重復(fù)的數(shù)據(jù)加工工作交給 pandas泞当,節(jié)省手工勞動(dòng)梧却,使用起來(lái)也比較方便奇颠,但輸出的格式并不太美觀。本文介紹 read_excel()
和 to_excel()
的部分細(xì)節(jié)放航,同時(shí)探討如何輸出一個(gè)較為美觀的 Excel 工作表烈拒。
pandas 讀取 Excel 文件
語(yǔ)法
DataFrame.read_excel()
的語(yǔ)法:
pandas.read_excel(io,
sheet_name=0,
header=0,
names=None,
index_col=None,
parse_cols=None,
usecols=None,
squeeze=False,
dtype=None,
engine=None,
converters=None,
true_values=None,
false_values=None,
skiprows=None,
nrows=None,
na_values=None,
keep_default_na=True,
verbose=False,
parse_dates=False,
date_parser=None,
thousands=None,
comment=None,
skip_footer=0,
skipfooter=0,
convert_float=True,
mangle_dupe_cols=True,
**kwds)
參數(shù)和返回值的說(shuō)明請(qǐng)參考 pandas 文檔 。
最簡(jiǎn)單的用法广鳍,只需要指定文件名參數(shù)荆几,支持 xls 文和 xlsx 文件格式,函數(shù)的返回值為 DataFrame 類(lèi)型的對(duì)象赊时。比如讀取 D 盤(pán)根目錄下的 source.xlsx 文件:
import pandas as pd
df1 = pd.read_excel(r'D:/source.xlsx)
如果想讀取 py 文件所在目錄下的某個(gè) Excel 文件吨铸,可以參考下面的代碼:
import pandas as pd
import os
# get path of current directory
curr_path = os.path.dirname(os.path.abspath(__file__))
fname = os.path.join(curr_path, 'users.xlsx')
df2 = pd.read_excel(fname)
指定要讀取的工作表
對(duì)于有多個(gè)工作表的 Excel 文件,pandas 默認(rèn)讀取第一個(gè)工作表( sheet_name=0
)祖秒。通過(guò)如下兩種方法可以指定要讀取的工作表:
# 方法一:通過(guò) index 指定工作表
df3 = pd.read_excel(file_name, sheet_name=0)
# 方法二:指定工作表名稱(chēng)
df4 = pd.read_excel(file_name, sheet_name='Sheet1')
導(dǎo)入指定列
如果只想導(dǎo)入指定的列诞吱,通過(guò) usecols
參數(shù)舟奠,比如想導(dǎo)入 A:D
和 H
這 4 列,有如下兩種方法:
df6 = pd.read_excel(r'D:/source.xlsx', usecols='A:D,H')
# 或者
df6 = pd.read_excel(r'D:/source.xlsx', usecols=[0,1,2,3,7])
指定表頭
默認(rèn)情況下房维,pandas 假定第一行為表頭 (header)鸭栖,如果 Excel 不是從第一行開(kāi)始,header
參數(shù)用于指定將哪一行作為表頭握巢,表頭在 DataFrame 中變成列索引 (column index) ,header 參數(shù)從 0 開(kāi)始松却,比如第二行作為 header暴浦,則:
df = pd.read_excel(file_name, header=1)
pandas 寫(xiě)入 Excel
語(yǔ)法
DataFrame.to_excel()
的語(yǔ)法:
DataFrame.to_excel(excel_writer,
sheet_name='Sheet1',
na_rep='',
float_format=None,
columns=None,
header=True,
index=True,
index_label=None,
startrow=0, startcol=0,
engine=None,
merge_cells=True,
encoding=None,
inf_rep='inf',
verbose=True,
freeze_panes=None)
參數(shù)和返回值的說(shuō)明請(qǐng)參考 pandas 文檔 。
數(shù)據(jù)寫(xiě)入 Excel晓锻,需要首先安裝一個(gè) engine歌焦,由 engine 負(fù)責(zé)將數(shù)據(jù)寫(xiě)入 Excel,pandas 使用 openpyx 或 xlsxwriter 作為寫(xiě)入引擎砚哆。
要將單一對(duì)象寫(xiě)入 Excel独撇,只需要指定 file name 即可:
import pandas as pd
import os
path = os.path.dirname(os.path.abspath(__file__))
source_file = os.path.join(path, 'source.xlsx')
output_file = os.path.join(path, 'output.xlsx')
df = pd.read_excel(source_file, sheet_name=0)
df.to_excel(output_file)
如果 output.xlsx 文件已經(jīng)存在,to_excel()
先刪除 output.xlsx 文件躁锁,然后重新生成一個(gè)新的文件纷铣,并且默認(rèn)添加一個(gè)索引列,索引為從 0 到 n 的整數(shù)战转。
不使用索引
導(dǎo)出 Excel搜立,一般不需要索引,將 index
參數(shù)設(shè)為 False 即可:
df.to_excel(output_file, index=False)
多工作表導(dǎo)出
導(dǎo)出多個(gè)工作表需要明確給出 excel writer engine槐秧,然后調(diào)用 DataFrame.to_excel()
方法:
import pandas as pd
import os
path = os.path.dirname(os.path.abspath(__file__))
source_file = os.path.join(path, 'source.xlsx')
output_file = os.path.join(path, 'output.xlsx')
df1 = pd.read_excel(source_file, sheet_name=0)
df2 = pd.read_excel(source_file, sheet_name=0, usecols='A:D,H')
with pd.ExcelWriter(output_file, engine='xlsxwriter') as writer:
df1.to_excel(writer, sheet_name='Sheet1', index=False)
df2.to_excel(writer, sheet_name='Sheet2', index=False)
工作表美化
pandas 導(dǎo)出的工作表并不美觀啄踊,如果想對(duì)工作表進(jìn)行美化的話(huà),可在 to_excel()
方法之后刁标,通過(guò)Excel writer engine 的格式設(shè)置的功能來(lái)設(shè)置格式颠通。根據(jù)測(cè)試, to_excel()
因?yàn)橄葎h除文件膀懈,所以也不能使用 Template 來(lái)保存預(yù)定義格式顿锰。所以如果需要導(dǎo)出有格式的 Excel 文件,比如作為報(bào)表輸出启搂,可考慮 Template + Excel writer engine 手工代碼的方式撵儿。
Creating Advanced Excel Workbooks with Python 這篇文章講到了一個(gè)方法,使用 xlsxwriter 的 add_table()
方法狐血,在 Excel 中創(chuàng)建一個(gè) Table 對(duì)象(中文經(jīng)常被稱(chēng)為智能表格)淀歇,然后選擇一個(gè)預(yù)定義的格式。我對(duì)代碼進(jìn)行了加工匈织,使之更具普適性:
import pandas as pd
import os
def get_col_widths(dataframe):
return [max([len(str(s)) for s in dataframe[col].values]
+ [len(col)]) for col in dataframe.columns]
def fmt_excel(writer, sheetname, dataframe):
# Get the workbook and the summary sheet so we can add the formatting
workbook = writer.book
worksheet = writer.sheets[sheetname]
col_count = dataframe.shape[1]
row_count = dataframe.shape[0]
col_names = []
for i in range(0, col_count):
col_names.append({'header': dataframe.columns[i]})
# rng = 'A1:H{}'.format(row_count + 1)
worksheet.add_table(0, 0, row_count,col_count-1, {
'columns': col_names,
'style': 'Table Style Medium 20'
})
# auto column size
col_widths = get_col_widths(dataframe)
for i, width in enumerate(col_widths):
worksheet.set_column(i, i, width)
path = os.path.dirname(os.path.abspath(__file__))
source_file = os.path.join(path, 'source.xlsx')
output_file = os.path.join(path, 'output.xlsx')
df = pd.read_excel(source_file, sheet_name=0)
writer = pd.ExcelWriter(output_file, engine='xlsxwriter')
df.to_excel(writer, 'Sheet1', index=False)
fmt_excel(writer, 'Sheet1', df)
writer.save()