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 pd
 
 
def pd_toExcel(data, fileName):  # pandas库储存数据到excel
    ids = []
    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)  # 创建DataFrame
    df.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 xw
  
def xw_toExcel(data, fileName):  # xlsxwriter库储存数据到excel
    workbook = 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 += 1
    workbook.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

相关推荐
FuckPatience27 分钟前
Visual Studio C# 项目中文件后缀简介
开发语言·c#
ZhengEnCi4 小时前
M3-markconv库找不到wkhtmltopdf问题
python
2301_764441337 小时前
LISA时空跃迁分析,地理时空分析
数据结构·python·算法
014-code7 小时前
订单超时取消与库存回滚的完整实现(延迟任务 + 状态机)
java·开发语言
lly2024067 小时前
组合模式(Composite Pattern)
开发语言
游乐码8 小时前
c#泛型约束
开发语言·c#
Dontla8 小时前
go语言Windows安装教程(安装go安装Golang安装)(GOPATH、Go Modules)
开发语言·windows·golang
chushiyunen8 小时前
python rest请求、requests
开发语言·python
cTz6FE7gA8 小时前
Python异步编程:从协程到Asyncio的底层揭秘
python
铁东博客8 小时前
Go实现周易大衍筮法三变取爻
开发语言·后端·golang