TH1/Tools/PrintExcelString.py

47 lines
1.7 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# -*- coding: utf-8 -*-
import sys
import openpyxl
import os
from datetime import datetime
def log(message):
print(f"[{datetime.now()}] {message}", file=sys.stderr)
def convert_excel_to_txt():
try:
excel_path = r"../Tools/Multilingual.xlsx"
txt_path = r"../Tools/MultilingualTxt.txt"
# 读取Excel文件跳过标题行
wb = openpyxl.load_workbook(excel_path)
ws = wb.active
records = []
for row in ws.iter_rows(min_row=2, values_only=True):
# 确保总是有6个字段空值转为空字符串
normalized_row = [str(cell).strip() if cell is not None else "" for cell in row]
if len(normalized_row) >= 6: # 只取前6列
records.append(normalized_row[:6])
else: # 不足6列则补齐空字符串
records.append(normalized_row + [""]*(6-len(normalized_row)))
if not records:
log("错误Excel中没有有效数据")
return False
# 写入TXT文件使用指定分隔符格式
os.makedirs(os.path.dirname(txt_path), exist_ok=True)
with open(txt_path, 'w', encoding='utf-8') as f:
for record in records:
# 确保总是6个字段空字段也会保留分隔符
line = '%$#@!'.join(field for field in record) + '!@#$%'
f.write(line)
log(f"成功转换 {len(records)} 条记录到TXT")
return True
except Exception as e:
log(f"转换失败: {str(e)}")
return False
if __name__ == "__main__":
sys.exit(0 if convert_excel_to_txt() else 1)