「工作中的那些Excel難題」 「1. 批量生成復(fù)雜報(bào)表」「問(wèn)題:」 「解決方案:」 「代碼示例:」 from openpyxl import Workbookimport os# 創(chuàng)建客戶列表customers = ['Alice', 'Bob', 'Charlie']# 批量生成Excel文件output_dir = 'reports'os.makedirs(output_dir, exist_ok=True)for customer in customers: wb = Workbook() ws = wb.active ws.title = 'Summary' ws['A1'] = f'Report for {customer}' ws['A2'] = 'Data goes here...' wb.save(f'{output_dir}/{customer}_report.xlsx')print(f'報(bào)表已保存到 {output_dir} 文件夾!') 「2. 自動(dòng)清洗臟數(shù)據(jù)」「問(wèn)題:」 「解決方案:」 「代碼示例:」
「3. 合并多個(gè)Excel文件」「問(wèn)題:」 「解決方案:」 「代碼示例:」 import pandas as pdimport os# 模擬文件路徑file_paths = ['file1.xlsx', 'file2.xlsx', 'file3.xlsx']# 合并所有文件combined_df = pd.concat(pd.read_excel(file) for file in file_paths)combined_df.to_excel('combined.xlsx', index=False)print('文件已合并為 combined.xlsx!') 「4. 自動(dòng)創(chuàng)建圖表」「問(wèn)題:」 「解決方案:」 「代碼示例:」
「5. 根據(jù)條件篩選并生成新文件」「問(wèn)題:」 「解決方案:」 「代碼示例:」 import pandas as pd# 模擬大數(shù)據(jù)data = { 'Name': ['Alice', 'Bob', 'Charlie', 'Daisy', 'Edward'], 'Age': [25, 30, 35, 40, 45], 'Department': ['HR', 'Sales', 'IT', 'Finance', 'Sales']}df = pd.DataFrame(data)# 條件篩選:只保留Sales部門(mén)的員工filtered_df = df[df['Department'] == 'Sales']# 保存篩選后的數(shù)據(jù)到新文件filtered_df.to_excel('filtered_data.xlsx', index=False)print('篩選完成,結(jié)果已保存為 filtered_data.xlsx') 如果你對(duì)Excel的操作已經(jīng)讓你懷疑人生,是時(shí)候?qū)W點(diǎn)Python了! |
|