本文目录导读:

Python + Pandas(最推荐)
基本操作示例
import pandas as pd
import os
# 读取单个Excel文件
df = pd.read_excel('input.xlsx')
# 批量读取多个文件
path = '数据文件夹/'
files = [f for f in os.listdir(path) if f.endswith('.xlsx')]
all_data = []
for file in files:
df = pd.read_excel(os.path.join(path, file))
all_data.append(df)
# 合并所有数据
combined_df = pd.concat(all_data, ignore_index=True)
# 数据处理示例
# 1. 删除空值
df_clean = combined_df.dropna()
# 2. 筛选特定条件
filtered = combined_df[combined_df['年龄'] > 18]
# 3. 添加计算列
combined_df['总价'] = combined_df['数量'] * combined_df['单价']
# 4. 分组统计
stats = combined_df.groupby('类别').agg({
'金额': ['sum', 'mean'],
'数量': 'count'
})
# 保存结果
combined_df.to_excel('汇总结果.xlsx', index=False)
Excel VBA 宏
Sub BatchProcess()
Dim ws As Worksheet
Dim rng As Range
Dim lastRow As Long
' 遍历所有工作表
For Each ws In ThisWorkbook.Worksheets
With ws
lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
' 处理数据
For i = 2 To lastRow ' 假设第一行是标题
' 计算新列
.Cells(i, 4).Value = .Cells(i, 2).Value * .Cells(i, 3).Value
' 条件格式化
If .Cells(i, 2).Value > 100 Then
.Cells(i, 2).Interior.Color = RGB(255, 0, 0)
End If
Next i
End With
Next ws
MsgBox "处理完成!"
End Sub
Python + openpyxl(Excel专用)
from openpyxl import load_workbook
import glob
# 批量处理多个Excel文件
for file in glob.glob('*.xlsx'):
wb = load_workbook(file)
for sheet in wb.sheetnames:
ws = wb[sheet]
# 处理每一行数据
for row in ws.iter_rows(min_row=2, max_row=ws.max_row):
cell_a = row[0].value # A列
cell_b = row[1].value # B列
if cell_a and cell_b:
# 在新列写入计算结果
ws.cell(row=row[0].row, column=4, value=cell_a * cell_b)
wb.save(f'processed_{file}')
## 4. **SQL 批量处理**
```sql
-- 将Excel导入数据库后的批量处理
UPDATE 销售表
SET 总价 = 数量 * 单价;
-- 批量更新特定条件
UPDATE 员工表
SET 部门 = CASE
WHEN 工资 > 10000 THEN '高级'
WHEN 工资 > 5000 THEN '中级'
ELSE '初级'
END;
-- 批量插入汇总数据
INSERT INTO 汇总表 (产品, 总销量, 总金额)
SELECT 产品, SUM(数量), SUM(金额)
FROM 销售明细
GROUP BY 产品;
实际应用场景示例
批量清洗数据
import pandas as pd
def clean_data(df):
# 去除空格
df = df.applymap(lambda x: x.strip() if isinstance(x, str) else x)
# 统一日期格式
df['日期'] = pd.to_datetime(df['日期'])
# 处理缺失值
df['金额'].fillna(0, inplace=True)
# 去除重复行
df.drop_duplicates(inplace=True)
return df
# 批量处理多个文件
output_dir = '清洗后的数据/'
for file in files:
df = pd.read_excel(file)
cleaned_df = clean_data(df)
cleaned_df.to_excel(f'{output_dir}clean_{file}', index=False)
批量生成报表
def generate_report(df, report_name):
# 按月统计
monthly = df.groupby(df['日期'].dt.month).agg({
'销售额': 'sum',
'成本': 'sum'
})
monthly['利润'] = monthly['销售额'] - monthly['成本']
# 生成Excel报表
with pd.ExcelWriter(f'reports/{report_name}_报表.xlsx') as writer:
monthly.to_excel(writer, sheet_name='月报表')
df.to_excel(writer, sheet_name='原始数据', index=False)
return monthly
推荐使用工具
- Python + Pandas:功能最强大,适合复杂逻辑
- Excel Power Query:无需编程,适合简单操作
- VBA宏:深度集成Excel
- KNIME/RapidMiner:可视化数据处理
需要根据你的具体需求选择合适的方法,如果需要更具体的示例,请告诉我你的数据结构和处理目标。