预览xls文件优化
This commit is contained in:
1 parent
ac04409e79
commit
df539f4ac1
8 files changed
+402
-43
No files matched your search
+116
-4
@@ -380,14 +380,86 @@ def _convert_excel_to_xlsx(content: bytes, ext: str) -> bytes:
|
||||
stderr = process.stderr.decode('utf-8', errors='ignore').strip()
|
||||
errors.append(f"{cmd}: {stderr or f'code={process.returncode}'}")
|
||||
|
||||
if _convert_excel_via_windows_office(input_path, output_path):
|
||||
with open(output_path, 'rb') as f:
|
||||
return f.read()
|
||||
errors.append("windows-office: failed to convert xls via WPS/MS Excel")
|
||||
|
||||
joined = "; ".join(errors) if errors else "no converter attempted"
|
||||
raise RuntimeError(f"failed to convert xls to xlsx: {joined}")
|
||||
|
||||
|
||||
def _load_excel_workbook(content: bytes, ext: str):
|
||||
def _convert_excel_via_windows_office(input_path: str, output_path: str) -> bool:
|
||||
"""
|
||||
在 Windows 环境下使用 WPS/MS Excel 将 `.xls` 转为 `.xlsx`。
|
||||
LibreOffice 不存在时,给在线预览提供兜底转换能力。
|
||||
"""
|
||||
if os.name != 'nt':
|
||||
return False
|
||||
|
||||
try:
|
||||
import pythoncom
|
||||
import win32com.client
|
||||
except ImportError:
|
||||
current_app.logger.warning("pywin32 not installed, cannot fallback to WPS/MS Excel for xls preview.")
|
||||
return False
|
||||
|
||||
app = None
|
||||
workbook = None
|
||||
pythoncom.CoInitialize()
|
||||
try:
|
||||
try:
|
||||
app = win32com.client.Dispatch("KET.Application")
|
||||
except Exception:
|
||||
app = win32com.client.Dispatch("Excel.Application")
|
||||
app.Visible = False
|
||||
app.DisplayAlerts = False
|
||||
workbook = app.Workbooks.Open(os.path.abspath(input_path))
|
||||
workbook.SaveAs(os.path.abspath(output_path), FileFormat=51) # 51 = xlOpenXMLWorkbook (.xlsx)
|
||||
workbook.Close(False)
|
||||
workbook = None
|
||||
app.Quit()
|
||||
app = None
|
||||
return os.path.exists(output_path)
|
||||
except Exception as exc:
|
||||
current_app.logger.warning("WPS/MS Excel conversion failed for xls preview: %s", exc)
|
||||
return False
|
||||
finally:
|
||||
try:
|
||||
if workbook is not None:
|
||||
workbook.Close(False)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
if app is not None:
|
||||
app.Quit()
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
pythoncom.CoUninitialize()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _detect_excel_format(content: bytes, ext: str) -> str:
|
||||
"""
|
||||
根据文件头兜底判断 Excel 实际格式,避免只依赖 URL/文件名扩展名。
|
||||
- OLE 复合文档头: 老式 `.xls`
|
||||
- ZIP 头: `.xlsx`
|
||||
"""
|
||||
normalized_ext = (ext or '').strip().lower()
|
||||
head = content[:8] if content else b''
|
||||
if head.startswith(b'PK\x03\x04'):
|
||||
return 'xlsx'
|
||||
if head.startswith(b'\xD0\xCF\x11\xE0'):
|
||||
return 'xls'
|
||||
return normalized_ext
|
||||
|
||||
|
||||
def _load_excel_workbook(content: bytes, ext: str):
|
||||
normalized_ext = _detect_excel_format(content, ext)
|
||||
if normalized_ext == 'xls':
|
||||
content = _convert_excel_to_xlsx(content, normalized_ext)
|
||||
content = _convert_excel_to_xlsx(content, 'xls')
|
||||
return load_workbook(filename=io.BytesIO(content), data_only=True, read_only=True)
|
||||
|
||||
|
||||
@@ -414,6 +486,29 @@ def get_oa_employees():
|
||||
return jsonify({'error': str(e)}), 500
|
||||
|
||||
|
||||
@chat_bp.route('/oa/resolve-names', methods=['GET'])
|
||||
@require_agent_permission
|
||||
def resolve_oa_names():
|
||||
dept_ids = request.args.get('department_ids', '').strip()
|
||||
sub_ids = request.args.get('subcompany_ids', '').strip()
|
||||
result = {}
|
||||
try:
|
||||
from app.services.oa_sqlserver import OASQLServerService
|
||||
if dept_ids:
|
||||
for did in dept_ids.split(','):
|
||||
did = did.strip()
|
||||
if did:
|
||||
result[f'dept_{did}'] = OASQLServerService.get_department_name(did)
|
||||
if sub_ids:
|
||||
for sid in sub_ids.split(','):
|
||||
sid = sid.strip()
|
||||
if sid:
|
||||
result[f'sub_{sid}'] = OASQLServerService.get_subcompany_name(sid)
|
||||
except Exception as e:
|
||||
current_app.logger.error(f"[OA-ResolveNames] Query failed: {e}")
|
||||
return jsonify(result)
|
||||
|
||||
|
||||
@chat_bp.route('/sessions', methods=['GET'])
|
||||
@require_agent_permission
|
||||
def get_chat_sessions():
|
||||
@@ -830,8 +925,25 @@ def preview_excel():
|
||||
try:
|
||||
wb = _load_excel_workbook(content, ext)
|
||||
except Exception as e:
|
||||
current_app.logger.warning("[excel-preview] parse workbook failed: %s", e)
|
||||
return jsonify({'error': 'failed to parse excel file'}), 422
|
||||
detected_ext = _detect_excel_format(content or b'', ext)
|
||||
current_app.logger.warning(
|
||||
"[excel-preview] parse workbook failed ext=%s detected_ext=%s size=%s name=%s url=%s err=%r",
|
||||
ext,
|
||||
detected_ext,
|
||||
len(content or b''),
|
||||
name,
|
||||
file_url,
|
||||
e,
|
||||
)
|
||||
payload = {'error': 'failed to parse excel file'}
|
||||
if current_app.config.get('DEBUG') or os.getenv('ENV_NAME', 'dev').strip().lower() == 'dev':
|
||||
payload.update({
|
||||
'detail': str(e),
|
||||
'ext': ext,
|
||||
'detected_ext': detected_ext,
|
||||
'size': len(content or b''),
|
||||
})
|
||||
return jsonify(payload), 422
|
||||
|
||||
if not wb.sheetnames:
|
||||
return jsonify({'error': 'workbook has no sheets'}), 422
|
||||
|
||||
@@ -1576,11 +1576,17 @@ def submit_leave_workflow():
|
||||
form_data = {
|
||||
'applicantName': _clean_str(data.get('applicantName')) or _clean_str(getattr(user, 'real_name', None)) or _clean_str(getattr(user, 'username', None)),
|
||||
'employeeId': _clean_str(data.get('employeeId')) or _clean_str(getattr(user, 'employee_id', None)) or _clean_str(getattr(user, 'username', None)),
|
||||
'applicantJobTitle': _clean_str(data.get('applicantJobTitle')),
|
||||
'applicantDepartmentId': _clean_str(data.get('applicantDepartmentId')),
|
||||
'applicantSubCompanyId1': _clean_str(data.get('applicantSubCompanyId1')),
|
||||
'applyTime': _clean_str(data.get('applyTime')),
|
||||
'fillerName': _clean_str(data.get('fillerName')) or _clean_str(getattr(user, 'real_name', None)) or _clean_str(getattr(user, 'username', None)),
|
||||
'agentUid': _clean_str(data.get('agentUid')),
|
||||
'agentEmployeeId': _clean_str(data.get('agentEmployeeId')),
|
||||
'agentName': _clean_str(data.get('agentName')),
|
||||
'agentJobTitle': _clean_str(data.get('agentJobTitle')),
|
||||
'agentDepartmentId': _clean_str(data.get('agentDepartmentId')),
|
||||
'agentSubCompanyId1': _clean_str(data.get('agentSubCompanyId1')),
|
||||
'leaveType': _clean_str(data.get('leaveType')),
|
||||
'startTime': _clean_str(data.get('startTime')),
|
||||
'endTime': _clean_str(data.get('endTime')),
|
||||
|
||||
Reference in new issue
Block a user