1.對比perl和python
分別嘗試用perl和python處理excel文件,發現perl的比較復雜,比如說read excel就有很多方式
Spreadsheet::Read
use Spreadsheet::ParseExcel
不同的method,對應的取sheet的cell方式也不一樣。更復雜的是處理含有中文內容的Excel。用perl目前沒有成功過。
對于python來說就比較簡單,目前使用openpyxl庫,處理起來清晰明了
2.python處理excel實例
下面給出一個python處理Excel的實例
用python完成兩個excel合并,要求如下:
1. 24xiaoxue.xlsx有A-G列,24zhongxue.xlsx有A-G列
2.用24zhongxue.xlsx的D列匹配24xiaoxue.xlsx的D列,如果有相同項,將24xiaoxue.xlsx相同項所在行添加到24zhongxue.xlsx行尾,并輸出到新的excel
3.支持中文內容
編碼聲明需要放在文件的第一行或第二行,一般使用?# -*- coding: 編碼格式 -*-
?這種形式。常見的編碼格式有?utf-8
、gbk
、gb2312
?等。
# -*- coding: gb2312 -*- #for 中文支持
import openpyxl# 定義文件路徑
file1 = '24zhongxue - 副本.xlsx' # 小學文件
file2 = '24xiaoxue - 副本.xlsx' # 中學文件
#file1 = 'xxxx.xlsx' # 小學文件
#file2 = 'xxxx.xlsx' # 中學文件
output_file = 'merged_result.xlsx' # 輸出文件# 加載兩個Excel文件
wb1 = openpyxl.load_workbook(file1)
wb2 = openpyxl.load_workbook(file2)# 獲取第一個工作表
ws1 = wb1.active
ws2 = wb2.active# 創建一個新的工作簿用于保存結果
wb_result = openpyxl.Workbook()
ws_result = wb_result.active# 將24zhongxue.xlsx的標題行復制到新工作簿
for col in range(1, 8): # A-G列for row in range(1,ws2.max_row+1):ws_result.cell(row=row, column=col).value = ws2.cell(row=row, column=col).value# 創建一個字典,用于存儲24xiaoxue.xlsx中D列的值和對應的行
match_dict = {}
for row in range(1, ws1.max_row + 1): # 從第1行開始key = ws1.cell(row=row, column=4).value # D列的值if key:match_dict[key] = row# 遍歷24zhongxue.xlsx的D列,查找匹配項
row_count = 1 # 新工作簿的行計數器
for row in range(1, ws2.max_row + 1): # 從第1行開始key = ws2.cell(row=row, column=4).value # D列的值if key and key in match_dict:# 如果找到匹配項,將24xiaoxue.xlsx中匹配的行復制到新工作簿matched_row = match_dict[key]for col in range(1, 8): # A-G列ws_result.cell(row=row, column=col+10).value = ws1.cell(row=matched_row, column=col).valuerow_count += 1else:# 如果沒有找到匹配項,將24zhongxue.xlsx的當前行復制到新工作簿#for couse Spreadsheet::ParseExcell in range(1, 8): # A-G列# ws_result.cell(row=row_count, column=col).value = ws2.cell(row=row, column=col).valuerow_count += 1# 保存結果到新的Excel文件
wb_result.save(output_file)print(f"合并完成,結果已保存到 {output_file}")