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)
相关推荐
Evan芙7 小时前
用fping编写脚本扫描10.0.0.0/24网段在线主机
linux·运维·网络·excel
SamDeepThinking12 小时前
基于CompletableFuture的主子任务并行处理架构实战:多渠道账单并发导入性能提升5倍的技术方案
java·后端·excel
SamDeepThinking12 小时前
88MB Excel文件导致系统崩溃?看我如何将内存占用降低
java·excel
咚咚王者12 小时前
人工智能之数据分析 Pandas:第二章 Series
人工智能·数据分析·pandas
ChrisitineTX12 小时前
警惕数据“陷阱”:Python 如何自动发现并清洗 Excel 中的异常值?
开发语言·python·excel
咚咚王者13 小时前
人工智能之数据分析 Pandas:第一章 简介和安装
人工智能·数据分析·pandas
wtsolutions13 小时前
Excel to JSON by WTSolutions 4.0.0 版本更新公告
json·excel·wps·插件·转换·加载项·wtsolutions
wtsolutions13 小时前
Excel to JSON by WTSolutions 4.0.0 Update Announcement
json·excel·wps·addin·wtsolutions·conversion
癫狂的兔子1 天前
【Office】【Excel】常用函数公式总结
excel
王大傻09282 天前
Series创建
pandas