👉 项目官网:https://www.python-office.com/ 👈

github star

大家好,这里是程序员晚枫,正在all in AI编程实战

今天这讲,我们深入学习 Excel 的高级操作——多Sheet处理与Sheet合并

1、读取指定Sheet

Excel 文件通常有多个 Sheet,如何读取指定的?

1
2
3
4
5
6
7
8
9
import office

# 读取指定的Sheet
df = office.excel.read(
path='工作簿.xlsx',
sheet='销售数据' # 指定Sheet名称
)

print(df)

也可以用 Sheet 序号(从0开始):

1
2
3
4
df = office.excel.read(
path='工作簿.xlsx',
sheet=1 # 读取第2个Sheet
)

2、读取所有Sheet

想把一个 Excel 的所有 Sheet 都读出来?

1
2
3
4
5
6
7
8
9
import office

# 读取所有Sheet
all_sheets = office.excel.read_all(path='工作簿.xlsx')

for sheet_name, df in all_sheets.items():
print(f'=== {sheet_name} ===')
print(df)
print()

3、合并同一个文件的所有Sheet

一个 Excel 有多个 Sheet,想合并成一个?

1
2
3
4
5
6
7
8
9
import office

# 合并所有Sheet
df = office.excel.merge_sheets(path='工作簿.xlsx')

# 保存
office.excel.write(path='合并结果.xlsx', data=df)

print('Sheet合并完成!')

4、把多个Sheet拆分成多个文件

一个 Excel 有很多 Sheet,想拆成单独的文件?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import office
import os

# 读取所有Sheet
all_sheets = office.excel.read_all(path='工作簿.xlsx')

# 保存到同名文件夹
output_folder = 'Sheet拆分结果'
os.makedirs(output_folder, exist_ok=True)

for sheet_name, df in all_sheets.items():
filename = os.path.join(output_folder, f'{sheet_name}.xlsx')
office.excel.write(path=filename, data=df)
print(f'已保存: {filename}')

print(f'共拆分 {len(all_sheets)} 个文件')

5、实战案例:汇总多个月份的Sheet

假设你有12个月的Excel数据,每个Sheet是一月的数据,要汇总成一年的总表:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import office
import pandas as pd

# 读取所有月份数据
all_sheets = office.excel.read_all(path='2024年数据.xlsx')

# 合并所有月份
all_data = []
for month, df in all_sheets.items():
df['月份'] = month # 标记来源月份
all_data.append(df)

# 合并
total_df = pd.concat(all_data, ignore_index=True)

# 保存全年数据
office.excel.write(path='2024年汇总.xlsx', data=total_df)

print('年度汇总完成!')

6、实战案例:批量处理多Sheet Excel

每月发工资条,要给每个员工生成一个 Sheet:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import office

# 读取员工数据
df = office.excel.read(path='员工工资.xlsx')

# 为每个员工创建一个Sheet
output_file = '工资条.xlsx'

for idx, row in df.iterrows():
sheet_name = row['姓名']
office.excel.write(
path=output_file,
data=[row],
sheet=sheet_name
)

print(f'已生成 {len(df)} 个工资条Sheet!')

7、常见问题

Q:Sheet名是中文乱码?

A:python-office 已处理中文编码,如仍有问题,检查 Excel 文件本身的编码。

Q:Sheet太多合并太慢?

A:可以只合并需要的 Sheet:

1
2
3
4
office.excel.merge_sheets(
path='工作簿.xlsx',
sheets=['1月', '2月', '3月'] # 只合并指定Sheet
)

8、下讲预告

学会了多Sheet处理,下一讲我们学 Excel高级:数据可视化——自动生成图表。

敬请期待!


有问题欢迎加微信 python-office 进群交流~

程序员晚枫专注AI编程培训,小白看完他和图灵社区合作的教程《30讲 · AI编程训练营》就能上手做AI项目。

🎓 AI 编程实战课程

想系统学习 AI 编程?程序员晚枫的 AI 编程实战课 帮你从零上手!