geometry-tower-defense/数据表/convert.py

90 lines
3.6 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.

import pandas as pd
import os
import csv
def is_valid_sheet(df):
if df.empty:
return False
# 过滤“全空行”的工作表
return not df.dropna(how='all').empty
def convert_excel_to_txt(folder_path='.'):
# 计数器,用于最后汇总
count = 0
# 固定从脚本所在目录读取,避免受运行时工作目录影响
script_dir = os.path.dirname(os.path.abspath(__file__))
scan_dir = script_dir if folder_path in ('.', '') else os.path.abspath(folder_path)
target_dir = os.path.join(os.path.dirname(__file__), '../Assets/GameMain/DataTables')
target_dir = os.path.abspath(target_dir)
# 确保目标目录存在
os.makedirs(target_dir, exist_ok=True)
for root, _, files in os.walk(scan_dir):
for file_name in files:
# 跳过 Excel 打开时生成的临时锁文件
if file_name.startswith('~$'):
continue
if file_name.endswith(('.xlsx', '.xls')):
file_path = os.path.join(root, file_name)
base_name = os.path.splitext(file_name)[0]
print(f"正在处理: {file_path}...")
try:
# 读取 Excel 中所有有效 Sheet
excel_file = pd.ExcelFile(file_path)
valid_sheets = []
for sheet_name in excel_file.sheet_names:
df = pd.read_excel(
excel_file,
sheet_name=sheet_name,
header=None,
keep_default_na=False,
)
if is_valid_sheet(df):
valid_sheets.append((sheet_name, df))
if not valid_sheets:
print(f"未找到有效 Sheet跳过: {file_path}")
continue
use_sheet_name_as_file_name = len(valid_sheets) > 1
for sheet_name, df in valid_sheets:
output_name = sheet_name if use_sheet_name_as_file_name else base_name
output_file = os.path.join(target_dir, f"{output_name}.txt")
# 预处理:将 NaN 替换为空字符串,否则导出会变成 "nan"
df = df.fillna('')
# 导出设置:
# 1. sep='\t' : 使用制表符分隔
# 2. quoting=csv.QUOTE_NONE + quotechar='\x00' : 不使用引号包裹字段,且 " 按原样输出
# 3. escapechar='\\' : 如果单元格内恰好有 Tab 键,会用反斜杠转义,防止数据列错位
df.to_csv(
output_file,
sep='\t',
index=False,
header=False,
encoding='utf-8',
quoting=csv.QUOTE_NONE,
quotechar='\x00',
escapechar='\\'
)
print(f"成功转换 -> {output_file} (Sheet: {sheet_name})")
count += 1
except Exception as e:
print(f"处理 {file_path} 时出错: {e}")
print(f"\n任务完成!共转换了 {count} 个文件。")
if __name__ == "__main__":
convert_excel_to_txt('.')
# --- 关键修改:在这里添加暂停 ---
print("\n" + "="*30)
input("按回车键(Enter)退出程序...")