Python操作Excel的10個(gè)必學(xué)腳本分享
前言
作為數(shù)據(jù)分析師、財(cái)務(wù)人員或辦公自動(dòng)化愛(ài)好者,Excel表格操作是我們?nèi)粘9ぷ髦胁豢苫蛉钡囊徊糠?。而Python憑借其強(qiáng)大的數(shù)據(jù)處理能力,可以極大地提升我們操作Excel的效率。本文將介紹10個(gè)必學(xué)的Python腳本,幫助你自動(dòng)化處理Excel表格,節(jié)省大量重復(fù)勞動(dòng)時(shí)間。
1. 讀取Excel文件
使用openpyxl或pandas庫(kù)可以輕松讀取Excel文件:
import pandas as pd # 讀取Excel文件 df = pd.read_excel('data.xlsx', sheet_name='Sheet1') # 顯示前5行數(shù)據(jù) print(df.head())
2. 寫入Excel文件
將處理后的數(shù)據(jù)保存回Excel:
# 創(chuàng)建一個(gè)DataFrame data = {'Name': ['John', 'Anna', 'Peter'], 'Age': [28, 24, 35]} df = pd.DataFrame(data) ???????# 寫入Excel文件 df.to_excel('output.xlsx', index=False)
3. 合并多個(gè)Excel文件
批量處理多個(gè)Excel文件時(shí),合并是非常常見(jiàn)的需求:
import os ???????# 獲取當(dāng)前目錄下所有xlsx文件 files = [f for f in os.listdir('.') if f.endswith('.xlsx')] # 合并所有文件 combined_df = pd.DataFrame() for file in files: df = pd.read_excel(file) combined_df = pd.concat([combined_df, df], ignore_index=True) # 保存合并后的文件 combined_df.to_excel('combined.xlsx', index=False)
4. 篩選和排序數(shù)據(jù)
Python可以輕松實(shí)現(xiàn)復(fù)雜的數(shù)據(jù)篩選和排序:
# 篩選年齡大于25的記錄 filtered_df = df[df['Age'] > 25] ???????# 按姓名升序排列 sorted_df = df.sort_values(by='Name') # 多重排序:先按年齡降序,再按姓名升序 multi_sorted = df.sort_values(by=['Age', 'Name'], ascending=[False, True])
5. 數(shù)據(jù)透視表
創(chuàng)建類似Excel中的數(shù)據(jù)透視表:
# 假設(shè)df包含'Salesperson', 'Region', 'Sales'等列 pivot_table = pd.pivot_table(df, values='Sales', index='Salesperson', columns='Region', aggfunc='sum', fill_value=0) pivot_table.to_excel('pivot_table.xlsx')
6. 條件格式設(shè)置
使用openpyxl實(shí)現(xiàn)類似Excel的條件格式:
from openpyxl import load_workbook from openpyxl.styles import PatternFill ???????# 加載工作簿 wb = load_workbook('data.xlsx') ws = wb.active # 創(chuàng)建紅色填充 red_fill = PatternFill(start_color='FF0000', end_color='FF0000', fill_type='solid') # 對(duì)B列中值小于50的單元格應(yīng)用紅色背景 for row in ws.iter_rows(min_col=2, max_col=2): for cell in row: if isinstance(cell.value, (int, float)) and cell.value < 50: cell.fill = red_fill # 保存修改 wb.save('formatted.xlsx')
7. 批量重命名工作表
from openpyxl import load_workbook ???????wb = load_workbook('data.xlsx') # 重命名所有工作表 for i, sheet in enumerate(wb.sheetnames, start=1): ws = wb[sheet] ws.title = f'Sheet_{i}' wb.save('renamed.xlsx')
8. 提取特定列到新文件
# 提取'Name'和'Email'列到新文件 extracted_df = df[['Name', 'Email']] extracted_df.to_excel('extracted_data.xlsx', index=False)
9. 自動(dòng)填充公式
from openpyxl import load_workbook wb = load_workbook('data.xlsx') ws = wb.active # 在C列添加SUM公式 for row in range(2, ws.max_row + 1): ws[f'C{row}'] = f'=SUM(A{row}:B{row})' wb.save('with_formulas.xlsx')
10. 發(fā)送帶Excel附件的郵件
import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.base import MIMEBase from email import encoders # 設(shè)置郵件內(nèi)容 msg = MIMEMultipart() msg['From'] = 'your_email@example.com' msg['To'] = 'recipient@example.com' msg['Subject'] = '自動(dòng)發(fā)送的Excel報(bào)表' # 添加正文 body = "請(qǐng)查收附件中的Excel報(bào)表。" msg.attach(MIMEText(body, 'plain')) # 添加附件 filename = "report.xlsx" attachment = open(filename, "rb") part = MIMEBase('application', 'octet-stream') part.set_payload(attachment.read()) encoders.encode_base64(part) part.add_header('Content-Disposition', f"attachment; filename= {filename}") msg.attach(part) # 發(fā)送郵件 server = smtplib.SMTP('smtp.example.com', 587) server.starttls() server.login('your_email@example.com', 'your_password') text = msg.as_string() server.sendmail('your_email@example.com', 'recipient@example.com', text) server.quit()
到此這篇關(guān)于Python操作Excel的10個(gè)必學(xué)腳本分享的文章就介紹到這了,更多相關(guān)Python操作Excel內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python中selenium操作下拉滾動(dòng)條的幾種方法匯總
這篇文章主要介紹了python中selenium操作下拉滾動(dòng)條的幾種方法匯總,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-07-07Python pywifi ERROR Open handle fai
這篇文章主要介紹了Python pywifi ERROR Open handle failed問(wèn)題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-06-06淺談Python在pycharm中的調(diào)試(debug)
今天小編就為大家分享一篇淺談Python在pycharm中的調(diào)試(debug),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-11-11關(guān)于python3的ThreadPoolExecutor線程池大小設(shè)置
這篇文章主要介紹了關(guān)于python3的ThreadPoolExecutor線程池大小設(shè)置,線程池的理想大小取決于被提交任務(wù)的類型以及所部署系統(tǒng)的特性,需要的朋友可以參考下2023-04-04基于Flask+websocket實(shí)現(xiàn)一個(gè)在線聊天室
在今天的互聯(lián)網(wǎng)時(shí)代,實(shí)時(shí)通信成為了許多應(yīng)用和服務(wù)的核心特色,在本文中,我們將介紹如何使用 Flask 和 Websockets 通過(guò) Flask-SocketIO 框架創(chuàng)建一個(gè)簡(jiǎn)單的在線聊天室,感興趣的可以跟隨小編一起了解下2023-09-09python實(shí)現(xiàn)FTP服務(wù)器服務(wù)的方法
本篇文章主要介紹了python實(shí)現(xiàn)FTP服務(wù)器的方法,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-04-04