python如何写数据到excel示例
python有多种写excel的方式,比如pandas、xlsxwriter、openpyxl等。
这里尝试基于这些方式,示例python写数据到excel的过程,示例程序整理自网络。
1 pandas写excel
1.1 pandas安装
这里尝试使用pandas库写excel文件,先安装pandas
pip install pandas==2.2 -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install openpyxl -i https://pypi.tuna.tsinghua.edu.cn/simple
pandas依赖openpyxl写数据到excel,所以在安装pandas同时需要安装openpyxl。
1.2 示例程序
写数据到excel的示例程序如下
import pandas as pddef pd_toExcel(data, fileName): # pandas库储存数据到excelids = []names = []prices = []for i in range(len(data)):ids.append(data[i]["id"])names.append(data[i]["name"])prices.append(data[i]["price"])dfData = { # 用字典设置DataFrame所需数据'序号': ids,'酒店': names,'价格': prices}df = pd.DataFrame(dfData) # 创建DataFramedf.to_excel(fileName, index=False) # 存表,False表示去除原始索引列(0,1,2...)testData = [{"id": 1, "name": "立智", "price": 100},{"id": 2, "name": "维纳", "price": 200},{"id": 3, "name": "如家", "price": 300},
]
fileName = 'pandas_case.xlsx'
pd_toExcel(testData, fileName)
2 xlsxwriter写excel
2.1 xlsxwriter安装
这里尝试使用xlsxwriter库写excel文件,先安装xlsxwriter
pip install xlsxwriter -i https://pypi.tuna.tsinghua.edu.cn/simple
2.2 示例程序
写数据到excel的示例程序如下
import xlsxwriter as xwdef xw_toExcel(data, fileName): # xlsxwriter库储存数据到excelworkbook = xw.Workbook(fileName) # 创建工作簿worksheet1 = workbook.add_worksheet("sheet1") # 创建子表worksheet1.activate() # 激活表title = ['序号', '酒店', '价格'] # 设置表头worksheet1.write_row('A1', title) # 从A1单元格开始写入表头i = 2 # 从第二行开始写入数据for j in range(len(data)):insertData = [data[j]["id"], data[j]["name"], data[j]["price"]]row = 'A' + str(i)worksheet1.write_row(row, insertData)i += 1workbook.close() # 关闭表testData = [{"id": 1, "name": "立智", "price": 100},{"id": 2, "name": "维纳", "price": 200},{"id": 3, "name": "如家", "price": 300},
]
fileName = 'xlsx_case.xlsx'
xw_toExcel(testData, fileName)
reference
---
Python写入Excel文件-多种实现方式(测试成功,附代码)
https://blog.csdn.net/qq_44695727/article/details/109174842