一、介紹
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/zh-tw/n/308739.html
微信掃一掃
支付寶掃一掃