#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import csv
from openpyxl import Workbook

def csv_to_excel(csv_file, excel_file):
    """将CSV文件转换为Excel文件"""
    wb = Workbook()
    ws = wb.active
    ws.title = "题库"
    
    with open(csv_file, 'r', encoding='utf-8-sig') as f:
        reader = csv.reader(f)
        for row_num, row in enumerate(reader, 1):
            for col_num, value in enumerate(row, 1):
                ws.cell(row=row_num, column=col_num, value=value)
    
    # 设置列宽
    for column in ws.columns:
        max_length = 0
        column_letter = column[0].column_letter
        for cell in column:
            try:
                if len(str(cell.value)) > max_length:
                    max_length = len(str(cell.value))
            except:
                pass
        adjusted_width = min(max_length + 2, 50)
        ws.column_dimensions[column_letter].width = adjusted_width
    
    wb.save(excel_file)

def main():
    """主函数：转换所有CSV文件为Excel"""
    output_dir = '/Users/moshui/Documents/survey/output'
    
    print("开始将CSV文件转换为Excel格式...")
    
    # 处理每个CSV文件
    for csv_file in os.listdir(output_dir):
        if csv_file.endswith('.csv'):
            csv_path = os.path.join(output_dir, csv_file)
            excel_file = csv_path.replace('.csv', '.xlsx')
            
            print(f"正在转换: {csv_file}")
            csv_to_excel(csv_path, excel_file)
            print(f"  已保存为: {os.path.basename(excel_file)}")
            
            # 删除原CSV文件
            os.remove(csv_path)
            print(f"  已删除原CSV文件")
    
    print("所有文件转换完成！")

if __name__ == "__main__":
    main()