一、介绍
Excel是一种常用的电子表格程序,可应用于各种应用场景,例如数据收集、数据整理、数据统计等。当我们需要将Excel中的数据导入到其他系统中时,我们通常需要将Excel数据进行一些转换和处理。在这个过程中,Python可以成为一个有用的工具。本文将介绍如何使用 Python 处理 Excel 数据,并通过示例代码演示一些常用的技巧,包括一键转换、批处理、筛选、排序等。
二、数据转换
在导出Excel文件时,常常需要将数据转换为不同的格式,如CSV格式、JSON格式等。Python内置的csv和json模块可以帮助我们快速转换数据。
import csv
import json
import openpyxl
# 将 Excel 文件转换成 CSV 格式
def excel_to_csv(excel_file, csv_file):
wb = openpyxl.load_workbook(excel_file)
ws = wb.active
with open(csv_file, 'w', newline='') as f:
writer = csv.writer(f)
for row in ws.rows:
writer.writerow([cell.value for cell in row])
# 将 Excel 文件转换成 JSON 格式
def excel_to_json(excel_file, json_file):
wb = openpyxl.load_workbook(excel_file)
ws = wb.active
rows = []
for row in ws.rows:
rows.append([cell.value for cell in row])
with open(json_file, 'w') as f:
json.dump(rows, f)
三、批处理
当需要对 Excel 文件夹中的多个文件进行批处理时,我们可以使用os模块遍历文件夹并批处理每个文件。
import openpyxl
import os
# 批量修改文件格式
def batch_process(folder_path, old_ext, new_ext):
for filename in os.listdir(folder_path):
if filename.endswith(old_ext):
excel_file = os.path.join(folder_path, filename)
new_name = os.path.splitext(filename)[0] + '.' + new_ext
new_file = os.path.join(folder_path, new_name)
wb = openpyxl.load_workbook(excel_file)
wb.save(new_file)
四、筛选和过滤
当Excel中含有大量数据时,我们可以使用pandas库来进行筛选和过滤操作。
import pandas as pd
import openpyxl
# 按条件筛选 Excel 中的数据
def filter_excel(excel_file, condition):
df = pd.read_excel(excel_file)
df_filtered = df[eval(condition)]
wb = openpyxl.Workbook()
ws = wb.active
for r in dataframe_to_rows(df_filtered, index=False, header=True):
ws.append(r)
wb.save(excel_file)
五、排序和分组
当需要按照某个关键字对 Excel 中的数据进行排序或者按照某个字段分组时,pandas库也可以起到很大的作用。
import pandas as pd
import openpyxl
# 按照某个关键字对 Excel 中的数据进行排序
def sort_excel(excel_file, column, ascending):
df = pd.read_excel(excel_file)
df_sorted = df.sort_values(by=column, ascending=ascending)
wb = openpyxl.Workbook()
ws = wb.active
for r in dataframe_to_rows(df_sorted,index=False, header=True):
ws.append(r)
wb.save(excel_file)
# 按照某个字段分组 Excel 中的数据
def group_by_excel(excel_file, column):
df = pd.read_excel(excel_file)
df_grouped = df.groupby(column)
wb = openpyxl.Workbook()
ws = wb.active
for key, group in df_grouped:
ws.append([key])
for r in dataframe_to_rows(group, index=False, header=True):
ws.append(r)
wb.save(excel_file)
六、结论
在处理数据时,Excel和Python都是非常有用的工具。本文介绍了如何使用Python进行Excel数据的转换、批处理、筛选、排序和分组,以及Python中的常用模块。希望能对需要处理Excel数据的读者有所帮助。
原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/308739.html
微信扫一扫
支付宝扫一扫