59 lines
1.7 KiB
Python
59 lines
1.7 KiB
Python
"""
|
|
backend/edkb_system/skills/excel_bridge.py
|
|
|
|
用途:Windows 环境下通过 Excel COM 将 .xls 转为 .xlsx。
|
|
依赖:pywin32(仅 Windows 且已安装 Microsoft Excel 时可用)。
|
|
逻辑:由 loader_excel._convert_xls_to_xlsx 在 soffice 失败后按需调用。
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
from pathlib import Path
|
|
|
|
|
|
def convert_with_excel(path: Path, output: Path) -> Path:
|
|
"""
|
|
使用 Microsoft Excel COM 将源表格另存为 .xlsx。
|
|
|
|
核心逻辑:启动 Excel.Application → Open → SaveAs(xlsx) → Quit。
|
|
|
|
Args:
|
|
path: 源 .xls 文件路径。
|
|
output: 目标 .xlsx 路径。
|
|
|
|
Returns:
|
|
成功写入的 output 路径。
|
|
|
|
Raises:
|
|
RuntimeError: 非 Windows、缺少 pywin32/Excel,或转换未产出目标文件。
|
|
"""
|
|
import os
|
|
|
|
if os.name != "nt":
|
|
raise RuntimeError("Excel COM conversion is only available on Windows")
|
|
|
|
try:
|
|
import win32com.client
|
|
except ImportError as exc:
|
|
raise RuntimeError("Excel COM conversion requires pywin32 on Windows") from exc
|
|
|
|
source = str(path.resolve())
|
|
target = str(output.resolve())
|
|
output.parent.mkdir(parents=True, exist_ok=True)
|
|
|
|
excel = win32com.client.Dispatch("Excel.Application")
|
|
excel.Visible = False
|
|
excel.DisplayAlerts = False
|
|
workbook = None
|
|
try:
|
|
workbook = excel.Workbooks.Open(source)
|
|
# 51 = xlOpenXMLWorkbook (.xlsx)
|
|
workbook.SaveAs(target, FileFormat=51)
|
|
finally:
|
|
if workbook is not None:
|
|
workbook.Close(SaveChanges=False)
|
|
excel.Quit()
|
|
|
|
if not output.exists():
|
|
raise RuntimeError(f"Excel COM did not produce output file: {output}")
|
|
return output
|