前言
Python 讀寫 Excel 文件的庫總體看還是很多的, 各有其優(yōu)缺點, 以下用一圖總結(jié)各庫的優(yōu)缺點, 同時對整體友好的庫重點介紹其使用教程。
Python 讀寫 Excel 庫簡介
庫名稱 | .xls | .xlsx | 讀取 | 寫入 | 修改 | 保存 | 格式調(diào)整 | 插入圖片 |
---|---|---|---|---|---|---|---|---|
xlrd | √ | √ | √ | × | × | × | × | × |
xlwt | √ | × | × | √ | √ | √ | √ | √ |
xlutils | √ | × | × | √ | √ | √ | × | × |
xlwings | √ | √ | √ | √ | √ | √ | √ | √ |
XlsxWriter | × | √ | × | √ | × | √ | √ | √ |
openpyxl | × | √ | √ | √ | √ | √ | √ | √ |
pandas | √ | √ | √ | √ | × | √ | × | × |
注: openpyxl: 優(yōu)點是不依賴Excel,計算機上不安裝Excel它也能讀寫Excel文件,所以適合做開發(fā)。文章來源:http://www.zghlxwxcb.cn/news/detail-667269.html
openpyxl 處理 Excel 文件教程
import openpyxl
def learn_openpyxl_deal_excel(fileName):
# https://openpyxl.readthedocs.io/en/stable/index.html
# 1 讀取文件
wb = openpyxl.load_workbook(fileName)
sheet = wb['Sheet1']
for sheet in wb: # 遍歷所有 sheet
print(sheet.title)
print(wb.sheetnames)
# 2 獲取單元格值
# 1) 指定坐標(biāo)范圍的值
cellss = sheet['A1:B5']
# 2) 指定列的值
cells = sheet['A']
cellss = sheet['A:C']
# 3) 指定行的值
cells = sheet[5]
cellss = sheet[5:7]
# 4) 獲取單元格的值 # 行下標(biāo)從 1 開始 列下標(biāo)從 0 開始
print(sheet[1][0].value)
# for cells in cellss:
# for cell in cells:
# print(cell.value)
# 3 寫入數(shù)據(jù)
cell = sheet['D4']
cell.value = '521'
sheet.cell(1, 1).value = "write_Data"
# 4 保存文件
wb.save('data/new_data_openpyxl.xlsx')
# 5 新建文件
workbook = openpyxl.Workbook()
worksheet = workbook.active
worksheet.title = 'newSheet'
# 插入數(shù)據(jù)
row = ["A", "B", "C"]
worksheet.append(row)
ws1 = workbook.create_sheet("Mysheet_End") # insert at the end (default)
ws2 = workbook.create_sheet("Mysheet_0", 0) # insert at first position
ws3 = workbook.create_sheet("Mysheet_pen", -1) # insert at the penultimate position
workbook.save('data/new_data_openpyxl_2.xlsx')
workbook.close()
if __name__ == "__main__":
xlsx_path = 'data/data.xlsx'
learn_openpyxl_deal_excel(xlsx_path)
pandas 處理 Excel 文件教程
import pandas as pd
def learn_pandas_deal_excel(fileName):
# https://pandas.pydata.org/docs/reference/api/pandas.read_excel.html#pandas.read_excel
# https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_excel.html?highlight=excel#pandas.DataFrame.to_excel
# 1 讀取文件的同時必須指定工作表:
sheet = pd.read_excel(fileName, sheet_name='Sheet1', index_col=False)
# 2 獲取單元格值
# 第一行為標(biāo)題行,所以從第二行才開始是其數(shù)據(jù)的第一行(idex=0)
# print(sheet.head(2))
# 1) 指定行的值 loc 根據(jù)所定義的index來獲取行
# print(sheet.loc[1])
# print(sheet.iloc[1])
# 2) 指定列的值
print(sheet.iloc[:, 0]) # 列下標(biāo)從 0 開始
# 3) 獲取單元格的值
# print(sheet.loc[0][2])
# 3 保存文件
df = pd.DataFrame([1, 2, 3])
df.to_excel("data/new_data_pandas.xlsx")
if __name__ == "__main__":
xls_path = 'data/data.xls'
xlsx_path = 'data/data.xlsx'
learn_pandas_deal_excel(xls_path)
learn_pandas_deal_excel(xlsx_path)
總結(jié)
本博客提到的所有代碼均可到我的 GitHub 下載。文章來源地址http://www.zghlxwxcb.cn/news/detail-667269.html
到了這里,關(guān)于Python 讀寫 Excel 文件庫推薦和使用教程的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!