pandas读取和写入excel

本文通过案例快速了解pandas读取excel文件的数据,同时写入新数据。

1、pd.read_excel()读取excel文件

python 复制代码
import pandas as pd

# 从当前工作目录读取名为 'test.xlsx' 的 Excel 文件
df = pd.read_excel('test.xlsx')

2、df.to_excel()写入 Excel 文件

python 复制代码
import pandas as pd

# 创建一个示例 DataFrame
data = {
    'Name': ['Alice', 'Bob', 'Charlie'],
    'Age': [25, 30, 35],
    'City': ['New York', 'London', 'Paris']
}
df = pd.DataFrame(data)

# 写入到当前目录的 'output.xlsx' 文件
# 如果不指定 sheet_name,默认为 'Sheet1'
df.to_excel('output.xlsx', sheet_name='People', index=False)

3、示例:读取文件后再生成新文件

python 复制代码
# 读取文件
file_path = r"D:\Users\Desktop\测试1.xlsx" 
df = pd.read_excel(file_path, engine='openpyxl', sheet_name='Sheet1')

# 定义写入新数据的列
df['code'] = None
df['result'] = None

# 写入新数据
df.at[index, 'code'] = "newcode"
df.at[index, 'result'] = "newresult"

# 写入新文件
excel_file = r'D:\Users\Desktop\结果2.xlsx'
df.to_excel(excel_file, index=False)
相关推荐
小白学大数据6 小时前
超简单:用 Python 让 Excel 飞起来:用 openpyxl 把重复报表整理交给脚本
开发语言·数据库·python·excel
Patrick在香港10 小时前
把 Claude 塞进 pandas 管道:7 条脏地址实测,5 条自动清洗、2 条被闸门拦下
python·pandas·etl·claude·数据清洗
SunnyDays101113 小时前
如何使用 Python 添加和编辑 Excel VBA 宏(无需安装 Excel)
开发语言·python·excel·vba
GHL28427109013 小时前
codex操作excel学习
学习·ai·word·excel
智购科技无人售货机工厂14 小时前
2026自动售货机云端API设计规范:从RESTful到GraphQL的接口演进~YH
android·人工智能·驱动开发·单片机·云原生·pandas·设计规范
quantdash_cc1 天前
批量请求和循环请求有什么区别?从 API 请求次数看量化数据获取的工程设计
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash
一晌小贪欢2 天前
python-第15天:Python 列表推导式
开发语言·python·excel·数据可视化·python办公
tryxr3 天前
Chat2Excel 项目通用服务开发
java·开发语言·excel·java项目开发
Jazz_z3 天前
使用 Python 合并与取消合并 Excel 单元格
开发语言·python·excel
2601_962381864 天前
Python办公联动:Excel数据一键自动生成PPT图表
python·数据分析·自动化·excel·ppt