1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
| import os import glob import openpyxl import pandas as pd from openpyxl.styles import Font, PatternFill, Alignment, Border, Side from openpyxl.utils import get_column_letter from datetime import datetime
def show_menu(): """显示菜单""" print("\n" + "=" * 55) print("Excel批量处理器 v1.0") print("=" * 55) print("1. 批量美化Excel格式") print("2. Excel批量转CSV") print("3. CSV批量转Excel") print("4. 合并多个Excel文件") print("5. 退出") print("=" * 55)
def get_folder_path(): """获取文件夹路径""" path = input("\n请输入文件夹路径(直接回车使用当前目录): ").strip() if not path: path = os.getcwd() if not os.path.isdir(path): print("❌ 路径不存在!") return None return path
def batch_beautify(): """批量美化""" folder = get_folder_path() if not folder: return excel_files = glob.glob(os.path.join(folder, "*.xlsx")) if not excel_files: print("⚠️ 未找到Excel文件") return print(f"\n🎨 开始批量美化 {len(excel_files)} 个文件...") for file in excel_files: try: beautify_excel(file) except Exception as e: print(f"处理失败: {e}") print("\n✅ 全部美化完成!")
def batch_excel_to_csv(): """批量Excel转CSV""" folder = get_folder_path() if folder: batch_excel_to_csv_impl(folder)
def batch_csv_to_excel(): """批量CSV转Excel""" folder = get_folder_path() if folder: batch_csv_to_excel_impl(folder)
def merge_files(): """合并文件""" folder = get_folder_path() if folder: output = input("输出文件名(默认:合并结果.xlsx): ").strip() or "合并结果.xlsx" merge_all_in_folder(folder, output)
def main(): while True: show_menu() choice = input("\n请选择功能(1-5): ").strip() if choice == "1": batch_beautify() elif choice == "2": batch_excel_to_csv() elif choice == "3": batch_excel_to_csv() elif choice == "4": merge_files() elif choice == "5": print("👋 感谢使用,再见!") break else: print("请输入1-5之间的数字!")
def beautify_excel(file_path): """美化单个文件""" wb = openpyxl.load_workbook(file_path) ws = wb.active header_fill = PatternFill(start_color="4472C4", end_color="4472C4", fill_type="solid") header_font = Font(bold=True, color="FFFFFF", size=12) for col in range(1, ws.max_column + 1): cell = ws.cell(row=1, column=col) cell.fill = header_fill cell.font = header_font cell.alignment = Alignment(horizontal="center") for row in range(2, ws.max_row + 1): for col in range(1, ws.max_column + 1): cell = ws.cell(row=row, column=col) if isinstance(cell.value, (int, float)): cell.number_format = '#,##0.00' for col in range(1, ws.max_column + 1): max_len = 0 col_letter = get_column_letter(col) for row in range(1, ws.max_row + 1): val = ws.cell(row=row, column=col).value if val: max_len = max(max_len, len(str(val))) ws.column_dimensions[col_letter].width = min(max_len + 2, 50) thin_border = Border( left=Side(style='thin'), right=Side(style='thin'), top=Side(style='thin'), bottom=Side(style='thin') ) for row in range(1, ws.max_row + 1): for col in range(1, ws.max_column + 1): ws.cell(row=row, column=col).border = thin_border new_path = file_path.replace('.xlsx', '_美化.xlsx') wb.save(new_path) wb.close() print(f" ✅ {os.path.basename(file_path)}")
def batch_excel_to_csv_impl(folder_path): """Excel转CSV实现""" excel_files = glob.glob(os.path.join(folder_path, "*.xlsx")) + \ glob.glob(os.path.join(folder_path, "*.xls")) if not excel_files: print("⚠️ 未找到Excel文件") return print(f"\n📂 开始批量转换 {len(excel_files)} 个文件...") success = 0 for file in excel_files: try: df = pd.read_excel(file) csv_path = file.replace('.xlsx', '.csv').replace('.xls', '.csv') df.to_csv(csv_path, index=False, encoding='utf-8-sig') print(f" ✅ {os.path.basename(file)}") success += 1 except Exception as e: print(f" ❌ {os.path.basename(file)}: {e}") print(f"\n📊 完成!成功转换 {success}/{len(excel_files)} 个文件")
def batch_csv_to_excel_impl(folder_path): """CSV转Excel实现""" csv_files = glob.glob(os.path.join(folder_path, "*.csv")) if not csv_files: print("⚠️ 未找到CSV文件") return print(f"\n📂 开始批量转换 {len(csv_files)} 个文件...") success = 0 for file in csv_files: try: df = pd.read_csv(file) excel_path = file.replace('.csv', '.xlsx') df.to_excel(excel_path, index=False, engine='openpyxl') print(f" ✅ {os.path.basename(file)}") success += 1 except Exception as e: print(f" ❌ {os.path.basename(file)}: {e}") print(f"\n📊 完成!成功转换 {success}/{len(csv_files)} 个文件")
def merge_all_in_folder(folder_path, output_path): """合并文件夹内所有Excel""" excel_files = glob.glob(os.path.join(folder_path, "*.xlsx")) + \ glob.glob(os.path.join(folder_path, "*.xls")) if not excel_files: print("⚠️ 未找到Excel文件") return print(f"\n🔗 开始合并 {len(excel_files)} 个文件...") all_data = [] for i, file in enumerate(excel_files, 1): print(f" [{i}/{len(excel_files)}] {os.path.basename(file)}") try: df = pd.read_excel(file) df['来源文件'] = os.path.basename(file) all_data.append(df) except Exception as e: print(f" ⚠️ 读取失败: {e}") if not all_data: print("❌ 没有成功读取任何文件") return merged = pd.concat(all_data, ignore_index=True) merged.to_excel(output_path, index=False, engine='openpyxl') print(f"\n✅ 合并完成!共 {len(merged)} 行数据") print(f"📊 保存为: {output_path}")
if __name__ == "__main__": if not os.path.exists("测试文件夹"): create_test_files() print("\n✅ 已创建测试数据在'测试文件夹'中") print("可以运行功能4(合并文件)测试效果") main()
|