深圳南山网站开发,网站首页网址,网站建设添加展示栏,wordpress 中国 论坛文章目录 前言Python 读写 Excel 库简介openpyxl 处理 Excel 文件教程pandas 处理 Excel 文件教程总结 前言
Python 读写 Excel 文件的库总体看还是很多的#xff0c; 各有其优缺点#xff0c; 以下用一图总结各库的优缺点#xff0c; 同时对整体友好的库重点介绍其使用教程… 文章目录 前言Python 读写 Excel 库简介openpyxl 处理 Excel 文件教程pandas 处理 Excel 文件教程总结 前言
Python 读写 Excel 文件的库总体看还是很多的 各有其优缺点 以下用一图总结各库的优缺点 同时对整体友好的库重点介绍其使用教程。
Python 读写 Excel 库简介
库名称.xls.xlsx读取写入修改保存格式调整插入图片xlrd√√√×××××xlwt√××√√√√√xlutils√××√√√××xlwings√√√√√√√√XlsxWriter×√×√×√√√openpyxl×√√√√√√√pandas√√√√×√××
注 openpyxl: 优点是不依赖Excel计算机上不安装Excel它也能读写Excel文件所以适合做开发。
openpyxl 处理 Excel 文件教程
import openpyxldef 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: # 遍历所有 sheetprint(sheet.title)print(wb.sheetnames)# 2 获取单元格值# 1) 指定坐标范围的值cellss sheet[A1:B5]# 2) 指定列的值cells sheet[A]cellss sheet[A:C]# 3) 指定行的值cells sheet[5]cellss sheet[5:7]# 4) 获取单元格的值 # 行下标从 1 开始 列下标从 0 开始print(sheet[1][0].value)# for cells in cellss:# for cell in cells:# print(cell.value)# 3 写入数据cell sheet[D4]cell.value 521sheet.cell(1, 1).value write_Data# 4 保存文件wb.save(data/new_data_openpyxl.xlsx)# 5 新建文件workbook openpyxl.Workbook()worksheet workbook.activeworksheet.title newSheet# 插入数据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 positionws3 workbook.create_sheet(Mysheet_pen, -1) # insert at the penultimate positionworkbook.save(data/new_data_openpyxl_2.xlsx)workbook.close()if __name__ __main__:xlsx_path data/data.xlsxlearn_openpyxl_deal_excel(xlsx_path)
pandas 处理 Excel 文件教程
import pandas as pddef 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?highlightexcel#pandas.DataFrame.to_excel# 1 读取文件的同时必须指定工作表sheet pd.read_excel(fileName, sheet_nameSheet1, index_colFalse)# 2 获取单元格值# 第一行为标题行所以从第二行才开始是其数据的第一行(idex0)# print(sheet.head(2))# 1) 指定行的值 loc 根据所定义的index来获取行# print(sheet.loc[1])# print(sheet.iloc[1])# 2) 指定列的值print(sheet.iloc[:, 0]) # 列下标从 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.xlsxlsx_path data/data.xlsxlearn_pandas_deal_excel(xls_path)learn_pandas_deal_excel(xlsx_path)
总结
本博客提到的所有代码均可到我的 GitHub 下载。