老板最近做得太过分了。他下班后给我寄了几百张表格,让我把内容合并成一张表格。
[En]
The boss has been going too far recently. He sent me hundreds of forms after work and asked me to merge the contents into one form.
还好我会Python,分分钟就搞定了,这要是换个不会Python的,不得加班到第二天天亮去了~
这样好用的技巧一定要跟大家分享,不用说太多,直接开始吧!
[En]
Such easy-to-use skills must be shared with you, without saying much, let’s start directly!
; 准备工作
我们需要先准备好表格数据,爬虫兄弟可以稍微爬一点,不,你可以让我直接拿到数据。
[En]
We need to prepare the table data first, the crawler brothers can climb a little bit, no, you can ask me to get the data directly.
表格内数据
我在这里只做演示,所以只使用了五个表,今天我们将市级合并到省级。
[En]
I only do the presentation here, so only five tables are used, and today we are merging the municipal level into the provincial level.
本文思路
- 将当前文件夹下所有的 excel 汇总到 广东省.xlsx
- 添加一个新的字段 城市,字段内容为商铺所在城市,这个字段放在最前面;
- 星级为 star_0 的数据全部不要
- 只要一条数据中有三个字段为空字段,整条数据都不需要;
- 将价格中的 ¥ 符号去掉
代码实现
所有的代码都是和你分享的,我不喜欢隐藏它。
[En]
All the code is shared with you, and I don’t like to hide it.
import glob
import openpyxl
Python学习交流群 815624229
workbook = openpyxl.Workbook()
sheet_total = workbook.active
sheet_total.append(['城市', '门店名称', '星级', '星级得分', '点评总数', '人均消费', '口味', '环境', '服务', '链接网址', '分类', '商圈', '详细地址', '推荐菜'])
def count_none(line):
"""返回空内容的数据"""
count = 0
for d in line:
if not d:
count += 1
return count
filenames = glob.glob('*/*.xlsx')
for filename in filenames:
# print(filename)
city = filename.split('.')[0].split('\\')[-1]
workbook_temp = openpyxl.load_workbook(filename)
sheet = workbook_temp.active
for row in sheet.iter_rows(min_row=2, min_col=1, max_col=sheet.max_column, max_row=sheet.max_row):
row_data = [col.value for col in row]
if row_data[1] == 'star_0':
continue
# 定义一个方法判断空字段的数量
if count_none(row_data) >= 3:
continue
# 去掉平均价格中的 ¥
if row_data[4]:
row_data[4] = row_data[4].strip('¥')
row_data.insert(0, city)
# print(row_data)
sheet_total.append(row_data)
# break # 调试只处理一个
workbook.save('广东省.xlsx')
效果
刚从烤箱里出来。非常新鲜。
[En]
It’s just out of the oven. It’s very fresh.
如您所见,数据已成功合并到一个表中。
[En]
As you can see, the data has been successfully merged into a table.
记住要喜欢你最喜欢的朋友的收藏。
[En]
Remember to like the collection of your favorite friends.
关注我分享更多技术干货
直接拿代码就等于嫖娼,喜欢收藏就是真理。
[En]
Directly take the code is equal to whoring, like the collection is the truth.
您的支持是我更新换代的动力!
[En]
Your support is the driving force for my renewal!
Original: https://www.cnblogs.com/hahaa/p/16145236.html
Author: 轻松学Python
Title: Python批量处理Excel表格,将多个表格内容合并到一个,提升工作效率!
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/499956/
转载文章受原作者版权保护。转载请注明原作者出处!