TH1/Tools/PrintExcelString.py

49 lines
1.6 KiB
Python

# -*- coding: utf-8 -*-
import sys
import io
# 强制 UTF-8 输出
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')
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"
wb = openpyxl.load_workbook(excel_path)
ws = wb.active
records = []
for row in ws.iter_rows(min_row=2, values_only=True):
normalized_row = [str(cell).strip() if cell is not None else "" for cell in row]
if len(normalized_row) >= 10:
records.append(normalized_row[:10])
else:
records.append(normalized_row + [""]*(10-len(normalized_row)))
if not records:
log("错误:Excel中没有有效数据")
return False
os.makedirs(os.path.dirname(txt_path), exist_ok=True)
with open(txt_path, 'w', encoding='utf-8') as f:
for record in records:
line = '%$#@!'.join(field for field in record) + '!@#$%'
f.write(line)
log(f"成功转换 {len(records)} 条记录到TXT")
return True
except Exception as e:
print(f"转换失败: {str(e)}", file=sys.stderr) # 只有错误才输出到 stderr
return False
if __name__ == "__main__":
sys.exit(0 if convert_excel_to_txt() else 1)