90 lines
3.5 KiB
Python
90 lines
3.5 KiB
Python
# -*- 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/DesignTable/UnitTypeData.xlsx"
|
||
txt_path = r"../Tools/DesignTable/TempTxt/UnitTypeData.txt"
|
||
|
||
# --- 核心修改开始 ---
|
||
|
||
# 1. 读取Excel文件并获取活动工作表
|
||
wb = openpyxl.load_workbook(excel_path)
|
||
ws = wb.active
|
||
|
||
# 2. 读取标题行(第一行)以确定列数
|
||
# 使用next()安全地获取迭代器的第一个元素,如果工作表为空则返回None
|
||
header_row = next(ws.iter_rows(min_row=1, max_row=1, values_only=True), None)
|
||
|
||
if not header_row:
|
||
log("错误:Excel文件为空或无法读取标题行。")
|
||
return False
|
||
|
||
# 3. 计算有效列数:从后往前找第一个有内容的单元格
|
||
# 这样做比len()更健壮,可以忽略尾部纯空的单元格
|
||
column_count = 0
|
||
for i in range(len(header_row) - 1, -1, -1):
|
||
if header_row[i] is not None and str(header_row[i]).strip() != '':
|
||
column_count = i + 1
|
||
break
|
||
|
||
if column_count == 0:
|
||
log("错误:Excel标题行(第一行)不包含任何有效数据,无法确定列数。")
|
||
return False
|
||
|
||
log(f"自动检测到标题行,有效列数为:{column_count}")
|
||
|
||
# --- 核心修改结束 ---
|
||
|
||
records = []
|
||
# 从第二行开始遍历数据行
|
||
for row in ws.iter_rows(min_row=2, values_only=True):
|
||
# 将所有单元格转换为字符串,None转为空字符串
|
||
normalized_row = [str(cell).strip() if cell is not None else "" for cell in row]
|
||
|
||
# 如果整行都是空的,则跳过,避免导出一堆空行
|
||
if all(cell == "" for cell in normalized_row):
|
||
continue
|
||
|
||
# 使用动态的column_count来处理每一行
|
||
# 先截取需要的列数
|
||
record = normalized_row[:column_count]
|
||
# 如果当前行数据不足,则用空字符串补齐
|
||
if len(record) < column_count:
|
||
record.extend([""] * (column_count - len(record)))
|
||
|
||
records.append(record)
|
||
|
||
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:
|
||
# 使用动态列数的数据进行拼接
|
||
line = '%$#@!'.join(field for field in record) + '!@#$%'
|
||
f.write(line + '\n') # 建议在行尾添加换行符,更符合文本文件规范
|
||
|
||
log(f"成功转换 {len(records)} 条记录到TXT文件(路径:{txt_path})")
|
||
return True
|
||
|
||
except FileNotFoundError:
|
||
log(f"错误:找不到Excel文件,请检查路径是否正确: {excel_path}")
|
||
return False
|
||
except Exception as e:
|
||
log(f"转换过程中发生未知错误: {str(e)}")
|
||
return False
|
||
|
||
if __name__ == "__main__":
|
||
sys.exit(0 if convert_excel_to_txt() else 1)
|