feat(panel): upgrade tabular exports to styled multi-sheet localized xlsx workbooks

This commit is contained in:
fish
2026-11-22 12:17:20 +09:00
parent a98fda8b44
commit eb8424d899
12 changed files with 4105 additions and 386 deletions
+1909 -141
View File
File diff suppressed because it is too large Load Diff
+35 -5
View File
@@ -11,7 +11,7 @@ import path from 'node:path';
import { DATA_DIR } from './config.mjs';
export const MAX_EXPORT_FILE_BYTES = 8 * 1024 * 1024;
export const ALLOWED_EXPORT_EXTENSIONS = Object.freeze(['.json', '.csv', '.md', '.txt']);
export const ALLOWED_EXPORT_EXTENSIONS = Object.freeze(['.json', '.csv', '.md', '.txt', '.xlsx']);
const ALLOWED_EXT_SET = new Set(ALLOWED_EXPORT_EXTENSIONS);
const MAX_RECENT_EXPORT_TRACK = 64;
@@ -38,6 +38,7 @@ export function isAuthorizedExportPath(filePath) {
function inferExtensionFromMime(mimeType) {
const lower = String(mimeType || '').toLowerCase();
if (lower.includes('spreadsheetml') || lower.includes('xlsx')) return '.xlsx';
if (lower.includes('csv')) return '.csv';
if (lower.includes('markdown')) return '.md';
if (lower.includes('plain')) return '.txt';
@@ -118,12 +119,33 @@ export function writeLocalExportFile(payload = {}, options = {}) {
if (typeof payload.content !== 'string') {
return { ok: false, status: 400, error: 'Export content must be a string' };
}
const byteLen = Buffer.byteLength(payload.content, 'utf8');
const isBase64 = payload.encoding === 'base64';
const { baseName, ext } = sanitizeLocalExportFilename(payload.filename, payload.mimeType);
let writeData;
let byteLen = 0;
if (isBase64) {
const cleanB64 = payload.content.replace(/\s+/g, '');
if (!cleanB64 || !/^[A-Za-z0-9+/=]+$/.test(cleanB64)) {
return { ok: false, status: 400, error: 'Invalid base64 export payload' };
}
const buf = Buffer.from(cleanB64, 'base64');
byteLen = buf.length;
if (byteLen > MAX_EXPORT_FILE_BYTES) {
return { ok: false, status: 413, error: 'Export file exceeds size limit' };
}
if (ext === '.xlsx' && (buf.length < 4 || buf[0] !== 0x50 || buf[1] !== 0x4b)) {
return { ok: false, status: 400, error: 'Invalid xlsx archive header' };
}
writeData = buf;
} else {
byteLen = Buffer.byteLength(payload.content, 'utf8');
if (byteLen > MAX_EXPORT_FILE_BYTES) {
return { ok: false, status: 413, error: 'Export file exceeds size limit' };
}
writeData = payload.content;
}
const { baseName, ext } = sanitizeLocalExportFilename(payload.filename, payload.mimeType);
const { dirPath, source } = resolveExportDirectory(options);
let targetPath = '';
@@ -132,7 +154,11 @@ export function writeLocalExportFile(payload = {}, options = {}) {
const candidateName = attempt === 0 ? `${baseName}${ext}` : `${baseName} (${attempt})${ext}`;
const candidatePath = path.join(dirPath, candidateName);
try {
writeFileSync(candidatePath, payload.content, { encoding: 'utf8', flag: 'wx' });
if (isBase64) {
writeFileSync(candidatePath, writeData, { flag: 'wx' });
} else {
writeFileSync(candidatePath, writeData, { encoding: 'utf8', flag: 'wx' });
}
targetPath = path.resolve(candidatePath);
finalFileName = candidateName;
break;
@@ -150,7 +176,11 @@ export function writeLocalExportFile(payload = {}, options = {}) {
const fallbackName = `${baseName}-${Date.now()}${ext}`;
const fallbackPath = path.join(dirPath, fallbackName);
try {
writeFileSync(fallbackPath, payload.content, { encoding: 'utf8', flag: 'wx' });
if (isBase64) {
writeFileSync(fallbackPath, writeData, { flag: 'wx' });
} else {
writeFileSync(fallbackPath, writeData, { encoding: 'utf8', flag: 'wx' });
}
targetPath = path.resolve(fallbackPath);
finalFileName = fallbackName;
} catch (err) {
+2 -2
View File
@@ -4,11 +4,11 @@
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>用量监控</title>
<link rel="stylesheet" href="/styles.css?v=1795316060647">
<link rel="stylesheet" href="/styles.css?v=1795317381498">
<script src="/preload.js"></script>
</head>
<body>
<div id="app-root"></div>
<script src="/app.js?v=1795316060647"></script>
<script src="/app.js?v=1795317381498"></script>
</body>
</html>
+1
View File
@@ -531,6 +531,7 @@ export function buildBundle(panelDir = PANEL_DIR) {
'src/core/formatters.js',
'src/core/stepInspector.js',
'src/core/settingsBackup.js',
'src/core/xlsxBuilder.js',
'src/core/reportExporter.js',
'src/core/httpClient.js',
'src/store/uiStore.js',
+136
View File
@@ -10,14 +10,55 @@ import { showUiToast } from '../store/uiStore.js';
import { callSidecarApi, isWindowOverlayMode } from './httpClient.js';
import { triggerTextFileDownload } from './settingsBackup.js';
import { copyPlainTextToClipboard } from './stepInspector.js';
import { uint8ArrayToBase64 } from './xlsxBuilder.js';
function isHostEmbeddedWebview() {
if (typeof window === 'undefined') return false;
return Boolean(window.sidecar?.fetch) || isWindowOverlayMode();
}
function triggerBinaryFileDownload(filename, bytes, mimeType) {
try {
if (
typeof Blob === 'undefined' ||
typeof URL === 'undefined' ||
typeof URL.createObjectURL !== 'function' ||
typeof document === 'undefined'
) {
return false;
}
const blob = new Blob([bytes], { type: mimeType });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.setAttribute('href', url);
a.setAttribute('download', String(filename || 'export.xlsx'));
a.style.display = 'none';
document.body?.appendChild?.(a);
a.click?.();
a.remove?.();
setTimeout(() => {
try {
URL.revokeObjectURL(url);
} catch {}
}, 1000);
return true;
} catch {
return false;
}
}
function getPickerTypesForFilename(filename, mimeType) {
const lower = String(filename || '').toLowerCase();
if (lower.endsWith('.xlsx') || String(mimeType || '').includes('spreadsheetml')) {
return [
{
description: 'Excel Workbook',
accept: {
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': ['.xlsx'],
},
},
];
}
if (lower.endsWith('.csv') || String(mimeType || '').includes('csv')) {
return [{ description: 'CSV', accept: { 'text/csv': ['.csv'] } }];
}
@@ -193,6 +234,101 @@ export async function exportTextFileWithFeedback(
return { ok: false, mode: 'failed' };
}
/**
* 统一二进制文件导出入口(用于原生 `.xlsx` Excel 工作簿)。
* 优先转 Base64 经本机后端落盘到 Downloads 并展示完整路径 + 「打开位置」直达按钮。
*
* @param {string} filename
* @param {Uint8Array} bytes
* @param {string} [mimeType='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet']
* @returns {Promise<{ ok: boolean, mode: 'local' | 'picker' | 'browser' | 'cancelled' | 'failed', filePath?: string, fileName?: string }>}
*/
export async function exportBinaryFileWithFeedback(
filename,
bytes,
mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
) {
const safeName = String(filename || 'export.xlsx');
if (!(bytes instanceof Uint8Array) || bytes.length === 0) {
showUiToast({ message: t('export.failed'), tone: 'warn', durationMs: 3600 });
return { ok: false, mode: 'failed' };
}
const base64Content = uint8ArrayToBase64(bytes);
const { res: localRes } = await requestLocalBackendExport({
filename: safeName,
content: base64Content,
encoding: 'base64',
mimeType,
});
if (localRes && localRes.ok && localRes.filePath) {
const savedPath = String(localRes.filePath);
const savedName = String(localRes.fileName || safeName);
showUiToast({
message: t('export.savedLocal', { file: savedName }),
detail: savedPath,
actionLabel: t('export.openFolder'),
onAction: () => {
void revealExportedFile(savedPath);
},
tone: 'ok',
durationMs: 7000,
});
return { ok: true, mode: 'local', filePath: savedPath, fileName: savedName };
}
if (isHostEmbeddedWebview()) {
showUiToast({
message: t('export.failed'),
detail: t('export.hostUnavailable'),
tone: 'warn',
durationMs: 5200,
});
return { ok: false, mode: 'failed' };
}
if (typeof window !== 'undefined' && typeof window.showSaveFilePicker === 'function') {
try {
const handle = await window.showSaveFilePicker({
suggestedName: safeName,
types: getPickerTypesForFilename(safeName, mimeType),
});
const writable = await handle.createWritable();
await writable.write(bytes);
await writable.close();
const pickedName = handle.name || safeName;
showUiToast({
message: t('export.savedPicked', { file: pickedName }),
tone: 'ok',
durationMs: 4200,
});
return { ok: true, mode: 'picker', fileName: pickedName };
} catch (err) {
if (err && err.name === 'AbortError') {
return { ok: false, mode: 'cancelled' };
}
}
}
const ok = triggerBinaryFileDownload(safeName, bytes, mimeType);
if (ok) {
showUiToast({
message: t('export.savedBrowser', { file: safeName }),
detail: t('export.savedBrowserHint'),
tone: 'info',
durationMs: 5000,
});
return { ok: true, mode: 'browser', fileName: safeName };
}
showUiToast({
message: t('export.failed'),
tone: 'warn',
durationMs: 3600,
});
return { ok: false, mode: 'failed' };
}
/**
* 复制文本到剪贴板并弹出轻量提示条。
*
File diff suppressed because it is too large Load Diff
+643
View File
@@ -0,0 +1,643 @@
/**
* @fileoverview 零外部依赖原生 Excel (`.xlsx` / ECMA-376 OOXML) 多工作表构建器 (`xlsxBuilder.js`)。
* 内置标准 IEEE 802.3 CRC-32 及 ZIP STORE 封装,支持:
* - 多 Sheet 分页、冻结首行表头、自动筛选下拉箭头;
* - 按中英文混合视觉宽度精确自动计算最佳列宽(彻底消除截断及 `###` / `1E+08` 科学计数法);
* - 原生数字格式(整数千分位 `#,##0`、货币 `$#,##0.00` / `$#,##0.0000`、原生百分比 `0.0%`、小数 `#,##0.0`);
* - 专业视觉样式(深石板蓝表头、斑马纹、汇总高亮、异常红底警示、压缩蓝底提示);
* - 全部字符串采用 `inlineStr` 并剔除 XML 1.0 非法控制符,天然免疫公式注入及 Excel 损坏警告。
*/
const INVALID_XML_CTRL_RE = /[\x00-\x08\x0B\x0C\x0E-\x1F\uFFFE\uFFFF]/g;
const INVALID_SHEET_NAME_RE = /[\\/?*[\]:]/g;
// --- 样式索引常量(对应下方 STYLES_XML 中的 cellXfs 顺序) ---
const STYLE_TEXT_LEFT = 1;
const STYLE_TEXT_LEFT_ALT = 2;
const STYLE_TEXT_CENTER = 3;
const STYLE_TEXT_CENTER_ALT = 4;
const STYLE_TEXT_RIGHT = 5;
const STYLE_TEXT_RIGHT_ALT = 6;
const STYLE_INT = 7;
const STYLE_INT_ALT = 8;
const STYLE_DEC1 = 9;
const STYLE_DEC1_ALT = 10;
const STYLE_DEC2 = 11;
const STYLE_DEC2_ALT = 12;
const STYLE_PCT = 13;
const STYLE_PCT_ALT = 14;
const STYLE_USD2 = 15;
const STYLE_USD2_ALT = 16;
const STYLE_USD4 = 17;
const STYLE_USD4_ALT = 18;
const STYLE_HEADER_LEFT = 19;
const STYLE_HEADER_CENTER = 20;
const STYLE_HEADER_RIGHT = 21;
const STYLE_DANGER_TEXT = 22;
const STYLE_DANGER_CENTER = 23;
const STYLE_DANGER_INT = 24;
const STYLE_DANGER_DEC1 = 25;
const STYLE_DANGER_DEC2 = 26;
const STYLE_DANGER_PCT = 27;
const STYLE_DANGER_USD4 = 28;
const STYLE_INFO_TEXT = 29;
const STYLE_INFO_CENTER = 30;
const STYLE_INFO_INT = 31;
const STYLE_INFO_DEC1 = 32;
const STYLE_INFO_DEC2 = 33;
const STYLE_INFO_PCT = 34;
const STYLE_INFO_USD4 = 35;
const STYLE_SUMMARY_LABEL = 36;
const STYLE_SUMMARY_CENTER = 37;
const STYLE_SUMMARY_TEXT_RIGHT = 38;
const STYLE_SUMMARY_INT = 39;
const STYLE_SUMMARY_DEC1 = 40;
const STYLE_SUMMARY_DEC2 = 41;
const STYLE_SUMMARY_PCT = 42;
const STYLE_SUMMARY_USD2 = 43;
const STYLE_SUMMARY_USD4 = 44;
const CRC32_TABLE = (() => {
const tbl = new Uint32Array(256);
for (let i = 0; i < 256; i += 1) {
let c = i;
for (let k = 0; k < 8; k += 1) {
c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
}
tbl[i] = c >>> 0;
}
return tbl;
})();
function computeCrc32(bytes) {
let crc = 0xffffffff;
for (let i = 0; i < bytes.length; i += 1) {
crc = CRC32_TABLE[(crc ^ bytes[i]) & 0xff] ^ (crc >>> 8);
}
return (crc ^ 0xffffffff) >>> 0;
}
function encodeUtf8Bytes(str) {
if (typeof TextEncoder !== 'undefined') {
return new TextEncoder().encode(String(str ?? ''));
}
if (typeof Buffer !== 'undefined') {
return new Uint8Array(Buffer.from(String(str ?? ''), 'utf8'));
}
const s = unescape(encodeURIComponent(String(str ?? '')));
const out = new Uint8Array(s.length);
for (let i = 0; i < s.length; i += 1) out[i] = s.charCodeAt(i);
return out;
}
/**
* 将 `Uint8Array` 编码为标准 Base64 字符串(兼容浏览器及 Node 环境)。
*
* @param {Uint8Array} bytes
* @returns {string}
*/
export function uint8ArrayToBase64(bytes) {
if (!(bytes instanceof Uint8Array)) return '';
if (typeof Buffer !== 'undefined') {
return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString('base64');
}
let binary = '';
const chunkSize = 0x8000;
for (let i = 0; i < bytes.length; i += chunkSize) {
const slice = bytes.subarray(i, i + chunkSize);
binary += String.fromCharCode.apply(null, slice);
}
return btoa(binary);
}
/**
* 标准零依赖 ZIP STORE 打包器(用于生成严格合规的 `.xlsx` OOXML 容器)。
*
* @param {Array<{ name: string, data: Uint8Array | string }>} entries
* @returns {Uint8Array}
*/
function buildZipStoreArchive(entries) {
const localParts = [];
const centralParts = [];
let offset = 0;
for (let i = 0; i < entries.length; i += 1) {
const nameBytes = encodeUtf8Bytes(entries[i].name);
const dataBytes =
entries[i].data instanceof Uint8Array
? entries[i].data
: encodeUtf8Bytes(entries[i].data);
const crc = computeCrc32(dataBytes);
const size = dataBytes.length;
// Local File Header (30 bytes + filename + data)
const lh = new Uint8Array(30 + nameBytes.length);
const lv = new DataView(lh.buffer);
lv.setUint32(0, 0x04034b50, true);
lv.setUint16(4, 20, true); // version needed: 2.0
lv.setUint16(6, 0x0800, true); // UTF-8 filename flag
lv.setUint16(8, 0, true); // compression: STORE
lv.setUint16(10, 0, true); // mod time
lv.setUint16(12, 0x5821, true); // mod date
lv.setUint32(14, crc, true);
lv.setUint32(18, size, true);
lv.setUint32(22, size, true);
lv.setUint16(26, nameBytes.length, true);
lv.setUint16(28, 0, true);
lh.set(nameBytes, 30);
localParts.push(lh, dataBytes);
// Central Directory Header (46 bytes + filename)
const ch = new Uint8Array(46 + nameBytes.length);
const cv = new DataView(ch.buffer);
cv.setUint32(0, 0x02014b50, true);
cv.setUint16(4, 20, true);
cv.setUint16(6, 20, true);
cv.setUint16(8, 0x0800, true);
cv.setUint16(10, 0, true);
cv.setUint16(12, 0, true);
cv.setUint16(14, 0x5821, true);
cv.setUint32(16, crc, true);
cv.setUint32(20, size, true);
cv.setUint32(24, size, true);
cv.setUint16(28, nameBytes.length, true);
cv.setUint16(30, 0, true);
cv.setUint16(32, 0, true);
cv.setUint16(34, 0, true);
cv.setUint16(36, 0, true);
cv.setUint32(38, 0, true);
cv.setUint32(42, offset, true);
ch.set(nameBytes, 46);
centralParts.push(ch);
offset += lh.length + dataBytes.length;
}
let cdSize = 0;
for (let i = 0; i < centralParts.length; i += 1) cdSize += centralParts[i].length;
// End of Central Directory Record (22 bytes)
const eocd = new Uint8Array(22);
const ev = new DataView(eocd.buffer);
ev.setUint32(0, 0x06054b50, true);
ev.setUint16(4, 0, true);
ev.setUint16(6, 0, true);
ev.setUint16(8, entries.length, true);
ev.setUint16(10, entries.length, true);
ev.setUint32(12, cdSize, true);
ev.setUint32(16, offset, true);
ev.setUint16(20, 0, true);
const totalLen = offset + cdSize + eocd.length;
const archive = new Uint8Array(totalLen);
let pos = 0;
for (let i = 0; i < localParts.length; i += 1) {
archive.set(localParts[i], pos);
pos += localParts[i].length;
}
for (let i = 0; i < centralParts.length; i += 1) {
archive.set(centralParts[i], pos);
pos += centralParts[i].length;
}
archive.set(eocd, pos);
return archive;
}
function escapeXmlText(val) {
return String(val ?? '')
.replace(INVALID_XML_CTRL_RE, '')
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&apos;');
}
function columnIndexToLetter(index) {
let n = index + 1;
let out = '';
while (n > 0) {
const rem = (n - 1) % 26;
out = String.fromCharCode(65 + rem) + out;
n = Math.floor((n - 1) / 26);
}
return out;
}
/**
* 估算文本在 Excel 单元格中的视觉字符宽度(中文/全角约占 2.05 宽,ASCII 约 1.05 宽)。
*/
function measureExcelVisualWidth(str) {
const s = String(str ?? '').replace(/\r?\n/g, ' ');
let w = 0;
for (let i = 0; i < s.length; i += 1) {
const code = s.charCodeAt(i);
if (
(code >= 0x2e80 && code <= 0x9fff) ||
(code >= 0xac00 && code <= 0xd7af) ||
(code >= 0xf900 && code <= 0xfaff) ||
(code >= 0xff00 && code <= 0xffef)
) {
w += 2.05;
} else {
w += 1.05;
}
}
return w;
}
function estimateFormattedValueWidth(val, colType) {
if (val === null || val === undefined || val === '') return 0;
if (typeof val === 'number' && Number.isFinite(val)) {
if (colType === 'int') {
return Math.round(val).toLocaleString('en-US').length * 1.1;
}
if (colType === 'usd2') {
return (`$${val.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`).length * 1.1;
}
if (colType === 'usd4') {
return (`$${val.toLocaleString('en-US', { minimumFractionDigits: 4, maximumFractionDigits: 4 })}`).length * 1.1;
}
if (colType === 'pct') {
return (`${(val * 100).toFixed(1)}%`).length * 1.1;
}
if (colType === 'dec1') {
return (`${val.toFixed(1)}`).length * 1.1;
}
if (colType === 'dec2') {
return (`${val.toFixed(2)}`).length * 1.1;
}
}
return measureExcelVisualWidth(String(val));
}
function sanitizeSheetName(rawName, usedNames) {
const base =
String(rawName || 'Sheet')
.replace(INVALID_XML_CTRL_RE, '')
.replace(INVALID_SHEET_NAME_RE, ' ')
.replace(/^'+|'+$/g, '')
.trim()
.slice(0, 31) || 'Sheet';
let name = base;
let seq = 2;
while (usedNames.has(name.toLowerCase())) {
const suffix = ` ${seq}`;
name = `${base.slice(0, Math.max(1, 31 - suffix.length))}${suffix}`;
seq += 1;
}
usedNames.add(name.toLowerCase());
return name;
}
function resolveHeaderStyle(col) {
const align =
col.align ||
(col.type === 'center'
? 'center'
: col.type && col.type !== 'text'
? 'right'
: 'left');
if (align === 'center') return STYLE_HEADER_CENTER;
if (align === 'right') return STYLE_HEADER_RIGHT;
return STYLE_HEADER_LEFT;
}
function resolveCellStyle(col, isAlt, rowTone) {
const colType = col.type || 'text';
if (rowTone === 'summary') {
if (colType === 'center') return STYLE_SUMMARY_CENTER;
if (colType === 'int') return STYLE_SUMMARY_INT;
if (colType === 'dec1') return STYLE_SUMMARY_DEC1;
if (colType === 'dec2') return STYLE_SUMMARY_DEC2;
if (colType === 'pct') return STYLE_SUMMARY_PCT;
if (colType === 'usd2') return STYLE_SUMMARY_USD2;
if (colType === 'usd4') return STYLE_SUMMARY_USD4;
if (colType === 'text_right' || col.align === 'right') return STYLE_SUMMARY_TEXT_RIGHT;
return STYLE_SUMMARY_LABEL;
}
if (rowTone === 'danger') {
if (colType === 'center') return STYLE_DANGER_CENTER;
if (colType === 'int') return STYLE_DANGER_INT;
if (colType === 'dec1') return STYLE_DANGER_DEC1;
if (colType === 'dec2') return STYLE_DANGER_DEC2;
if (colType === 'pct') return STYLE_DANGER_PCT;
if (colType === 'usd2' || colType === 'usd4') return STYLE_DANGER_USD4;
return STYLE_DANGER_TEXT;
}
if (rowTone === 'info') {
if (colType === 'center') return STYLE_INFO_CENTER;
if (colType === 'int') return STYLE_INFO_INT;
if (colType === 'dec1') return STYLE_INFO_DEC1;
if (colType === 'dec2') return STYLE_INFO_DEC2;
if (colType === 'pct') return STYLE_INFO_PCT;
if (colType === 'usd2' || colType === 'usd4') return STYLE_INFO_USD4;
return STYLE_INFO_TEXT;
}
if (colType === 'center') return isAlt ? STYLE_TEXT_CENTER_ALT : STYLE_TEXT_CENTER;
if (colType === 'text_right') return isAlt ? STYLE_TEXT_RIGHT_ALT : STYLE_TEXT_RIGHT;
if (colType === 'int') return isAlt ? STYLE_INT_ALT : STYLE_INT;
if (colType === 'dec1') return isAlt ? STYLE_DEC1_ALT : STYLE_DEC1;
if (colType === 'dec2') return isAlt ? STYLE_DEC2_ALT : STYLE_DEC2;
if (colType === 'pct') return isAlt ? STYLE_PCT_ALT : STYLE_PCT;
if (colType === 'usd2') return isAlt ? STYLE_USD2_ALT : STYLE_USD2;
if (colType === 'usd4') return isAlt ? STYLE_USD4_ALT : STYLE_USD4;
return isAlt ? STYLE_TEXT_LEFT_ALT : STYLE_TEXT_LEFT;
}
function buildStylesXml() {
return `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
<numFmts count="6">
<numFmt numFmtId="164" formatCode="#,##0"/>
<numFmt numFmtId="165" formatCode="#,##0.0"/>
<numFmt numFmtId="166" formatCode="#,##0.00"/>
<numFmt numFmtId="167" formatCode="$#,##0.00"/>
<numFmt numFmtId="168" formatCode="$#,##0.0000"/>
<numFmt numFmtId="169" formatCode="0.0%"/>
</numFmts>
<fonts count="5">
<font><sz val="10"/><color rgb="FF1E293B"/><name val="Microsoft YaHei UI"/></font>
<font><b/><sz val="10"/><color rgb="FFFFFFFF"/><name val="Microsoft YaHei UI"/></font>
<font><sz val="10"/><color rgb="FFB91C1C"/><name val="Microsoft YaHei UI"/></font>
<font><sz val="10"/><color rgb="FF0369A1"/><name val="Microsoft YaHei UI"/></font>
<font><b/><sz val="10"/><color rgb="FF0F172A"/><name val="Microsoft YaHei UI"/></font>
</fonts>
<fills count="7">
<fill><patternFill patternType="none"/></fill>
<fill><patternFill patternType="gray125"/></fill>
<fill><patternFill patternType="solid"><fgColor rgb="FF1E293B"/></patternFill></fill>
<fill><patternFill patternType="solid"><fgColor rgb="FFF8FAFC"/></patternFill></fill>
<fill><patternFill patternType="solid"><fgColor rgb="FFFEF2F2"/></patternFill></fill>
<fill><patternFill patternType="solid"><fgColor rgb="FFF0F9FF"/></patternFill></fill>
<fill><patternFill patternType="solid"><fgColor rgb="FFEFF6FF"/></patternFill></fill>
</fills>
<borders count="4">
<border><left/><right/><top/><bottom/><diagonal/></border>
<border>
<left style="thin"><color rgb="FFE2E8F0"/></left>
<right style="thin"><color rgb="FFE2E8F0"/></right>
<top style="thin"><color rgb="FFE2E8F0"/></top>
<bottom style="thin"><color rgb="FFE2E8F0"/></bottom>
<diagonal/>
</border>
<border>
<left style="thin"><color rgb="FF334155"/></left>
<right style="thin"><color rgb="FF334155"/></right>
<top style="thin"><color rgb="FF334155"/></top>
<bottom style="medium"><color rgb="FF0F172A"/></bottom>
<diagonal/>
</border>
<border>
<left style="thin"><color rgb="FFCBD5E1"/></left>
<right style="thin"><color rgb="FFCBD5E1"/></right>
<top style="thin"><color rgb="FF94A3B8"/></top>
<bottom style="medium"><color rgb="FF475569"/></bottom>
<diagonal/>
</border>
</borders>
<cellStyleXfs count="1">
<xf numFmtId="0" fontId="0" fillId="0" borderId="0"/>
</cellStyleXfs>
<cellXfs count="45">
<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/>
<xf numFmtId="0" fontId="0" fillId="0" borderId="1" xfId="0" applyFont="1" applyBorder="1" applyAlignment="1"><alignment horizontal="left" vertical="center"/></xf>
<xf numFmtId="0" fontId="0" fillId="3" borderId="1" xfId="0" applyFont="1" applyFill="1" applyBorder="1" applyAlignment="1"><alignment horizontal="left" vertical="center"/></xf>
<xf numFmtId="0" fontId="0" fillId="0" borderId="1" xfId="0" applyFont="1" applyBorder="1" applyAlignment="1"><alignment horizontal="center" vertical="center"/></xf>
<xf numFmtId="0" fontId="0" fillId="3" borderId="1" xfId="0" applyFont="1" applyFill="1" applyBorder="1" applyAlignment="1"><alignment horizontal="center" vertical="center"/></xf>
<xf numFmtId="0" fontId="0" fillId="0" borderId="1" xfId="0" applyFont="1" applyBorder="1" applyAlignment="1"><alignment horizontal="right" vertical="center"/></xf>
<xf numFmtId="0" fontId="0" fillId="3" borderId="1" xfId="0" applyFont="1" applyFill="1" applyBorder="1" applyAlignment="1"><alignment horizontal="right" vertical="center"/></xf>
<xf numFmtId="164" fontId="0" fillId="0" borderId="1" xfId="0" applyNumberFormat="1" applyFont="1" applyBorder="1" applyAlignment="1"><alignment horizontal="right" vertical="center"/></xf>
<xf numFmtId="164" fontId="0" fillId="3" borderId="1" xfId="0" applyNumberFormat="1" applyFont="1" applyFill="1" applyBorder="1" applyAlignment="1"><alignment horizontal="right" vertical="center"/></xf>
<xf numFmtId="165" fontId="0" fillId="0" borderId="1" xfId="0" applyNumberFormat="1" applyFont="1" applyBorder="1" applyAlignment="1"><alignment horizontal="right" vertical="center"/></xf>
<xf numFmtId="165" fontId="0" fillId="3" borderId="1" xfId="0" applyNumberFormat="1" applyFont="1" applyFill="1" applyBorder="1" applyAlignment="1"><alignment horizontal="right" vertical="center"/></xf>
<xf numFmtId="166" fontId="0" fillId="0" borderId="1" xfId="0" applyNumberFormat="1" applyFont="1" applyBorder="1" applyAlignment="1"><alignment horizontal="right" vertical="center"/></xf>
<xf numFmtId="166" fontId="0" fillId="3" borderId="1" xfId="0" applyNumberFormat="1" applyFont="1" applyFill="1" applyBorder="1" applyAlignment="1"><alignment horizontal="right" vertical="center"/></xf>
<xf numFmtId="169" fontId="0" fillId="0" borderId="1" xfId="0" applyNumberFormat="1" applyFont="1" applyBorder="1" applyAlignment="1"><alignment horizontal="right" vertical="center"/></xf>
<xf numFmtId="169" fontId="0" fillId="3" borderId="1" xfId="0" applyNumberFormat="1" applyFont="1" applyFill="1" applyBorder="1" applyAlignment="1"><alignment horizontal="right" vertical="center"/></xf>
<xf numFmtId="167" fontId="0" fillId="0" borderId="1" xfId="0" applyNumberFormat="1" applyFont="1" applyBorder="1" applyAlignment="1"><alignment horizontal="right" vertical="center"/></xf>
<xf numFmtId="167" fontId="0" fillId="3" borderId="1" xfId="0" applyNumberFormat="1" applyFont="1" applyFill="1" applyBorder="1" applyAlignment="1"><alignment horizontal="right" vertical="center"/></xf>
<xf numFmtId="168" fontId="0" fillId="0" borderId="1" xfId="0" applyNumberFormat="1" applyFont="1" applyBorder="1" applyAlignment="1"><alignment horizontal="right" vertical="center"/></xf>
<xf numFmtId="168" fontId="0" fillId="3" borderId="1" xfId="0" applyNumberFormat="1" applyFont="1" applyFill="1" applyBorder="1" applyAlignment="1"><alignment horizontal="right" vertical="center"/></xf>
<xf numFmtId="0" fontId="1" fillId="2" borderId="2" xfId="0" applyFont="1" applyFill="1" applyBorder="1" applyAlignment="1"><alignment horizontal="left" vertical="center"/></xf>
<xf numFmtId="0" fontId="1" fillId="2" borderId="2" xfId="0" applyFont="1" applyFill="1" applyBorder="1" applyAlignment="1"><alignment horizontal="center" vertical="center"/></xf>
<xf numFmtId="0" fontId="1" fillId="2" borderId="2" xfId="0" applyFont="1" applyFill="1" applyBorder="1" applyAlignment="1"><alignment horizontal="right" vertical="center"/></xf>
<xf numFmtId="0" fontId="2" fillId="4" borderId="1" xfId="0" applyFont="1" applyFill="1" applyBorder="1" applyAlignment="1"><alignment horizontal="left" vertical="center"/></xf>
<xf numFmtId="0" fontId="2" fillId="4" borderId="1" xfId="0" applyFont="1" applyFill="1" applyBorder="1" applyAlignment="1"><alignment horizontal="center" vertical="center"/></xf>
<xf numFmtId="164" fontId="2" fillId="4" borderId="1" xfId="0" applyNumberFormat="1" applyFont="1" applyFill="1" applyBorder="1" applyAlignment="1"><alignment horizontal="right" vertical="center"/></xf>
<xf numFmtId="165" fontId="2" fillId="4" borderId="1" xfId="0" applyNumberFormat="1" applyFont="1" applyFill="1" applyBorder="1" applyAlignment="1"><alignment horizontal="right" vertical="center"/></xf>
<xf numFmtId="166" fontId="2" fillId="4" borderId="1" xfId="0" applyNumberFormat="1" applyFont="1" applyFill="1" applyBorder="1" applyAlignment="1"><alignment horizontal="right" vertical="center"/></xf>
<xf numFmtId="169" fontId="2" fillId="4" borderId="1" xfId="0" applyNumberFormat="1" applyFont="1" applyFill="1" applyBorder="1" applyAlignment="1"><alignment horizontal="right" vertical="center"/></xf>
<xf numFmtId="168" fontId="2" fillId="4" borderId="1" xfId="0" applyNumberFormat="1" applyFont="1" applyFill="1" applyBorder="1" applyAlignment="1"><alignment horizontal="right" vertical="center"/></xf>
<xf numFmtId="0" fontId="3" fillId="5" borderId="1" xfId="0" applyFont="1" applyFill="1" applyBorder="1" applyAlignment="1"><alignment horizontal="left" vertical="center"/></xf>
<xf numFmtId="0" fontId="3" fillId="5" borderId="1" xfId="0" applyFont="1" applyFill="1" applyBorder="1" applyAlignment="1"><alignment horizontal="center" vertical="center"/></xf>
<xf numFmtId="164" fontId="3" fillId="5" borderId="1" xfId="0" applyNumberFormat="1" applyFont="1" applyFill="1" applyBorder="1" applyAlignment="1"><alignment horizontal="right" vertical="center"/></xf>
<xf numFmtId="165" fontId="3" fillId="5" borderId="1" xfId="0" applyNumberFormat="1" applyFont="1" applyFill="1" applyBorder="1" applyAlignment="1"><alignment horizontal="right" vertical="center"/></xf>
<xf numFmtId="166" fontId="3" fillId="5" borderId="1" xfId="0" applyNumberFormat="1" applyFont="1" applyFill="1" applyBorder="1" applyAlignment="1"><alignment horizontal="right" vertical="center"/></xf>
<xf numFmtId="169" fontId="3" fillId="5" borderId="1" xfId="0" applyNumberFormat="1" applyFont="1" applyFill="1" applyBorder="1" applyAlignment="1"><alignment horizontal="right" vertical="center"/></xf>
<xf numFmtId="168" fontId="3" fillId="5" borderId="1" xfId="0" applyNumberFormat="1" applyFont="1" applyFill="1" applyBorder="1" applyAlignment="1"><alignment horizontal="right" vertical="center"/></xf>
<xf numFmtId="0" fontId="4" fillId="6" borderId="3" xfId="0" applyFont="1" applyFill="1" applyBorder="1" applyAlignment="1"><alignment horizontal="left" vertical="center"/></xf>
<xf numFmtId="0" fontId="4" fillId="6" borderId="3" xfId="0" applyFont="1" applyFill="1" applyBorder="1" applyAlignment="1"><alignment horizontal="center" vertical="center"/></xf>
<xf numFmtId="0" fontId="4" fillId="6" borderId="3" xfId="0" applyFont="1" applyFill="1" applyBorder="1" applyAlignment="1"><alignment horizontal="right" vertical="center"/></xf>
<xf numFmtId="164" fontId="4" fillId="6" borderId="3" xfId="0" applyNumberFormat="1" applyFont="1" applyFill="1" applyBorder="1" applyAlignment="1"><alignment horizontal="right" vertical="center"/></xf>
<xf numFmtId="165" fontId="4" fillId="6" borderId="3" xfId="0" applyNumberFormat="1" applyFont="1" applyFill="1" applyBorder="1" applyAlignment="1"><alignment horizontal="right" vertical="center"/></xf>
<xf numFmtId="166" fontId="4" fillId="6" borderId="3" xfId="0" applyNumberFormat="1" applyFont="1" applyFill="1" applyBorder="1" applyAlignment="1"><alignment horizontal="right" vertical="center"/></xf>
<xf numFmtId="169" fontId="4" fillId="6" borderId="3" xfId="0" applyNumberFormat="1" applyFont="1" applyFill="1" applyBorder="1" applyAlignment="1"><alignment horizontal="right" vertical="center"/></xf>
<xf numFmtId="167" fontId="4" fillId="6" borderId="3" xfId="0" applyNumberFormat="1" applyFont="1" applyFill="1" applyBorder="1" applyAlignment="1"><alignment horizontal="right" vertical="center"/></xf>
<xf numFmtId="168" fontId="4" fillId="6" borderId="3" xfId="0" applyNumberFormat="1" applyFont="1" applyFill="1" applyBorder="1" applyAlignment="1"><alignment horizontal="right" vertical="center"/></xf>
</cellXfs>
</styleSheet>`;
}
function buildWorksheetXml(sheet, isFirstSheet) {
const columns = Array.isArray(sheet.columns) ? sheet.columns : [];
const rows = Array.isArray(sheet.rows) ? sheet.rows : [];
const hasAutoFilter = sheet.autoFilter !== false;
const headerPad = hasAutoFilter ? 5.5 : 3.8;
const colWidths = columns.map((col) => {
const headerW = measureExcelVisualWidth(col.header || '') + headerPad;
return Math.max(Number(col.minWidth || 9), headerW);
});
const rowXmls = [];
// Row 1: Header
const headerCells = [];
for (let c = 0; c < columns.length; c += 1) {
const ref = `${columnIndexToLetter(c)}1`;
const styleId = resolveHeaderStyle(columns[c]);
headerCells.push(
`<c r="${ref}" t="inlineStr" s="${styleId}"><is><t xml:space="preserve">${escapeXmlText(columns[c].header || '')}</t></is></c>`
);
}
rowXmls.push(`<row r="1" ht="26" customHeight="1">${headerCells.join('')}</row>`);
// Data Rows
for (let r = 0; r < rows.length; r += 1) {
const rowObj = rows[r];
const rowValues = Array.isArray(rowObj) ? rowObj : Array.isArray(rowObj?.values) ? rowObj.values : [];
const rowTone = !Array.isArray(rowObj) && rowObj?.tone ? rowObj.tone : '';
const isAlt = r % 2 === 1;
const excelRowIdx = r + 2;
const cellXmls = [];
for (let c = 0; c < columns.length; c += 1) {
const col = columns[c];
const rawVal = rowValues[c];
const ref = `${columnIndexToLetter(c)}${excelRowIdx}`;
const isCellObj = rawVal && typeof rawVal === 'object' && !Array.isArray(rawVal);
const val = isCellObj ? rawVal.value : rawVal;
const cellCol = isCellObj && rawVal.type ? { ...col, type: rawVal.type } : col;
const styleId = resolveCellStyle(cellCol, isAlt, rowTone);
const estW = estimateFormattedValueWidth(val, cellCol.type) + 3.8;
const maxW = Number(col.maxWidth || 52);
if (estW > colWidths[c]) {
colWidths[c] = Math.min(maxW, estW);
}
if (val === null || val === undefined || val === '') {
cellXmls.push(`<c r="${ref}" s="${styleId}"/>`);
} else if (typeof val === 'number' && Number.isFinite(val)) {
cellXmls.push(`<c r="${ref}" s="${styleId}"><v>${val}</v></c>`);
} else {
const textVal = String(val);
cellXmls.push(
`<c r="${ref}" t="inlineStr" s="${styleId}"><is><t xml:space="preserve">${escapeXmlText(textVal)}</t></is></c>`
);
}
}
const rowHeight = rowTone === 'summary' ? 24 : 21;
rowXmls.push(`<row r="${excelRowIdx}" ht="${rowHeight}" customHeight="1">${cellXmls.join('')}</row>`);
}
const colsXml = columns
.map((_, idx) => {
const w = Math.max(8, Math.min(64, +colWidths[idx].toFixed(1)));
return `<col min="${idx + 1}" max="${idx + 1}" width="${w}" customWidth="1"/>`;
})
.join('');
const lastCol = columnIndexToLetter(Math.max(0, columns.length - 1));
const lastRow = Math.max(1, rows.length + 1);
// 若末尾包含合计行,自动筛选区自动排除合计行,避免按列排序时把合计行混入明细
let filterEndRow = lastRow;
while (filterEndRow > 1) {
const tailRow = rows[filterEndRow - 2];
if (tailRow && !Array.isArray(tailRow) && tailRow.tone === 'summary') {
filterEndRow -= 1;
} else {
break;
}
}
const autoFilterXml =
hasAutoFilter && columns.length > 0 && filterEndRow > 1
? `<autoFilter ref="A1:${lastCol}${filterEndRow}"/>`
: '';
const tabSel = isFirstSheet ? ' tabSelected="1"' : '';
const freezeXml =
sheet.freezeHeader !== false
? '<pane ySplit="1" topLeftCell="A2" activePane="bottomLeft" state="frozen"/>'
: '';
return `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
<dimension ref="A1:${lastCol}${lastRow}"/>
<sheetViews><sheetView${tabSel} workbookViewId="0">${freezeXml}</sheetView></sheetViews>
<sheetFormatPr defaultRowHeight="21"/>
<cols>${colsXml}</cols>
<sheetData>${rowXmls.join('')}</sheetData>
${autoFilterXml}
</worksheet>`;
}
/**
* 将结构化多工作表数据编译为标准 `.xlsx` 二进制字节流 (`Uint8Array`)。
*
* @param {Array<{
* name: string,
* columns: Array<{ header: string, type?: 'text'|'center'|'int'|'dec1'|'dec2'|'pct'|'usd2'|'usd4', align?: 'left'|'center'|'right', minWidth?: number, maxWidth?: number }>,
* rows: Array<Array<unknown> | { values: Array<unknown>, tone?: ''|'danger'|'info'|'summary' }>,
* autoFilter?: boolean,
* freezeHeader?: boolean,
* }>} sheets
* @returns {Uint8Array}
*/
export function buildXlsxWorkbookBytes(sheets) {
const validSheets = (Array.isArray(sheets) ? sheets : []).filter(
(s) => s && Array.isArray(s.columns) && s.columns.length > 0
);
if (validSheets.length === 0) {
validSheets.push({
name: 'Sheet1',
columns: [{ header: 'Empty', type: 'text', minWidth: 14 }],
rows: [],
});
}
const usedNames = new Set();
const normalizedSheets = validSheets.map((s) => ({
...s,
safeName: sanitizeSheetName(s.name, usedNames),
}));
const contentOverrides = [
'<Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>',
'<Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/>',
...normalizedSheets.map(
(_, idx) =>
`<Override PartName="/xl/worksheets/sheet${idx + 1}.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>`
),
].join('');
const contentTypesXml = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>
<Default Extension="xml" ContentType="application/xml"/>
${contentOverrides}
</Types>`;
const rootRelsXml = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/>
</Relationships>`;
const wbSheetsXml = normalizedSheets
.map(
(s, idx) =>
`<sheet name="${escapeXmlText(s.safeName)}" sheetId="${idx + 1}" r:id="rId${idx + 1}"/>`
)
.join('');
const workbookXml = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
<sheets>${wbSheetsXml}</sheets>
</workbook>`;
const wbRelsList = [
...normalizedSheets.map(
(_, idx) =>
`<Relationship Id="rId${idx + 1}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet${idx + 1}.xml"/>`
),
`<Relationship Id="rId${normalizedSheets.length + 1}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>`,
].join('');
const wbRelsXml = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
${wbRelsList}
</Relationships>`;
const archiveEntries = [
{ name: '[Content_Types].xml', data: contentTypesXml },
{ name: '_rels/.rels', data: rootRelsXml },
{ name: 'xl/workbook.xml', data: workbookXml },
{ name: 'xl/_rels/workbook.xml.rels', data: wbRelsXml },
{ name: 'xl/styles.xml', data: buildStylesXml() },
...normalizedSheets.map((s, idx) => ({
name: `xl/worksheets/sheet${idx + 1}.xml`,
data: buildWorksheetXml(s, idx === 0),
})),
];
return buildZipStoreArchive(archiveEntries);
}
+4
View File
@@ -267,6 +267,8 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
'cons.workspaceSessions': '{count} sessions',
'cons.workspaceJumpTip': 'Click to inspect latest session in this project',
'cons.exportMenuAria': 'Export and report actions',
'cons.exportXlsx': 'Export Excel (.xlsx)',
'cons.exportXlsxTip': 'Export styled multi-sheet Excel workbook with auto column width and alignment',
'cons.exportCsv': 'Export CSV',
'cons.exportCsvTip': 'Export current usage range as CSV',
'cons.exportCsvDone': 'Exported',
@@ -410,6 +412,8 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
'steps.inspPromptTitle': 'Turn Prompt',
'steps.inspRowClickTip': 'Click row to inspect step details',
'steps.exportMenuAria': 'Export and report actions',
'steps.exportXlsx': 'Export Excel (.xlsx)',
'steps.exportXlsxTip': 'Export styled multi-sheet Excel workbook for steps and model summary',
'steps.exportCsv': 'Export CSV',
'steps.exportCsvTip': 'Export current steps table as CSV',
'steps.exportCsvDone': 'Exported',
+4
View File
@@ -267,6 +267,8 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
'cons.workspaceSessions': '{count} 会话',
'cons.workspaceJumpTip': '点击跳转到该项目最近会话',
'cons.exportMenuAria': '导出及报告选项',
'cons.exportXlsx': '导出 Excel (.xlsx)',
'cons.exportXlsxTip': '导出多工作表排版精美的 Excel 报表(自动列宽、千分位及对齐)',
'cons.exportCsv': '导出 CSV',
'cons.exportCsvTip': '导出当前统计区间用量明细为 CSV',
'cons.exportCsvDone': '已导出',
@@ -410,6 +412,8 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
'steps.inspPromptTitle': '本轮提问',
'steps.inspRowClickTip': '点击查看单步详情',
'steps.exportMenuAria': '导出及报告选项',
'steps.exportXlsx': '导出 Excel (.xlsx)',
'steps.exportXlsxTip': '导出排版精美的步骤明细及模型汇总 Excel 报表',
'steps.exportCsv': '导出 CSV',
'steps.exportCsvTip': '导出当前步骤明细为 CSV 文件',
'steps.exportCsvDone': '已导出',
+15 -12
View File
@@ -34,13 +34,14 @@ import {
} from '../core/formatters.js';
import { scaleBucketsExact } from '../../shared/telemetry-display-rules.mjs';
import {
buildConsumptionCsv,
buildConsumptionExportBaseName,
buildConsumptionMarkdownReport,
buildConsumptionXlsx,
sanitizeExportFilename,
} from '../core/reportExporter.js';
import {
copyTextWithFeedback,
exportTextFileWithFeedback,
exportBinaryFileWithFeedback,
} from '../core/fileExportClient.js';
import { i18nStore, isEnglishLocale, t } from '../i18n/index.js';
import { createSvgIcon } from '../icons/SvgIcon.js';
@@ -223,10 +224,10 @@ export const ConsumptionView = defineComponent({
className: 'cons-export-menu',
items: [
{
key: 'csv',
key: 'xlsx',
icon: 'download',
label: t('cons.exportCsv'),
title: t('cons.exportCsvTip'),
label: t('cons.exportXlsx'),
title: t('cons.exportXlsxTip'),
onSelect: () => {
const cons = latestSlice?.consumption;
if (!cons) return;
@@ -235,14 +236,16 @@ export const ConsumptionView = defineComponent({
showUpstreamModel: latestSlice?.showUpstreamModel,
orchestratorIdMode: latestSlice?.orchestratorIdMode,
};
const csv = buildConsumptionCsv(cons, latestSlice?.modelBreakdown || [], {
const bytes = buildConsumptionXlsx(cons, latestSlice?.modelBreakdown || [], {
displaySettings,
});
const rKey = cons.selectedRange?.key || latestSlice?.range || 'all';
void exportTextFileWithFeedback(
sanitizeExportFilename(`usage-${rKey}`, 'csv'),
csv,
'text/csv;charset=utf-8'
const baseName = buildConsumptionExportBaseName(
cons,
latestSlice?.range || 'all'
);
void exportBinaryFileWithFeedback(
sanitizeExportFilename(baseName, 'xlsx'),
bytes
);
},
},
@@ -2240,7 +2243,7 @@ export const ConsumptionView = defineComponent({
patchText(outputUsageLabel, t('cons.outputUsage'));
consExportMenu.refs.setAriaLabel(t('cons.exportMenuAria'));
consExportMenu.refs.updateItemLabels({
csv: { label: t('cons.exportCsv'), title: t('cons.exportCsvTip') },
xlsx: { label: t('cons.exportXlsx'), title: t('cons.exportXlsxTip') },
md: { label: t('cons.exportMd'), title: t('cons.exportMdTip') },
});
patchText(trendTitleSpan, t('cons.trendTitle'));
+17 -12
View File
@@ -42,13 +42,14 @@ import {
getStepSelectionKey,
} from '../core/stepInspector.js';
import {
buildStepsCsv,
buildStepsExportBaseName,
buildStepsMarkdownReport,
buildStepsXlsx,
sanitizeExportFilename,
} from '../core/reportExporter.js';
import {
copyTextWithFeedback,
exportTextFileWithFeedback,
exportBinaryFileWithFeedback,
} from '../core/fileExportClient.js';
import { createSvgIcon, patchSvgIcon } from '../icons/SvgIcon.js';
import { ActionMenu } from '../components/ui/ActionMenu.js';
@@ -468,20 +469,24 @@ export const StepsDetailView = defineComponent({
className: 'steps-export-menu',
items: [
{
key: 'csv',
key: 'xlsx',
icon: 'download',
label: t('steps.exportCsv'),
title: t('steps.exportCsvTip'),
label: t('steps.exportXlsx'),
title: t('steps.exportXlsxTip'),
onSelect: () => {
if (currentTableSteps.length === 0) return;
const csv = buildStepsCsv(currentTableSteps, {
const bytes = buildStepsXlsx(currentTableSteps, {
title: latestSlice?.activeConversation?.title || '',
cascadeId: latestSlice?.cascadeId || latestSlice?.activeConversation?.cascadeId || '',
displaySettings: currentDisplaySettings,
});
const title = latestSlice?.activeConversation?.title || latestSlice?.cascadeId || 'steps';
void exportTextFileWithFeedback(
sanitizeExportFilename(`steps-${title}`, 'csv'),
csv,
'text/csv;charset=utf-8'
const baseName = buildStepsExportBaseName(
latestSlice?.activeConversation?.title || '',
latestSlice?.cascadeId || latestSlice?.activeConversation?.cascadeId || ''
);
void exportBinaryFileWithFeedback(
sanitizeExportFilename(baseName, 'xlsx'),
bytes
);
},
},
@@ -1042,7 +1047,7 @@ export const StepsDetailView = defineComponent({
if (!inspCopyTimer) patchText(inspCopyLabel, t('steps.inspCopy'));
stepsExportMenu.refs.setAriaLabel(t('steps.exportMenuAria'));
stepsExportMenu.refs.updateItemLabels({
csv: { label: t('steps.exportCsv'), title: t('steps.exportCsvTip') },
xlsx: { label: t('steps.exportXlsx'), title: t('steps.exportXlsxTip') },
md: { label: t('steps.exportMd'), title: t('steps.exportMdTip') },
});
lastAnomalyStripSig = '';
@@ -1415,16 +1415,47 @@ test('Feature 10: StepsDetailView live search, dynamic diagnostic chips, and cli
assert.equal(view.refs.stepInspectorDrawerEl.hasAttribute('hidden'), true);
});
test('Feature 11: RFC-4180 formula-safe CSV and Markdown report export for Steps and Consumption views', async () => {
test('Feature 11: native multi-sheet localized XLSX, formula-safe CSV and bilingual Markdown report export', async () => {
const {
escapeCsvCell,
sanitizeExportFilename,
buildStepsCsv,
buildStepsXlsx,
buildStepsMarkdownReport,
buildStepsExportBaseName,
buildConsumptionCsv,
buildConsumptionXlsx,
buildConsumptionMarkdownReport,
buildConsumptionExportBaseName,
} = await import('../src/core/reportExporter.js');
function parseZipStoreEntries(bytes) {
assert.equal(bytes instanceof Uint8Array, true);
assert.equal(bytes[0], 0x50);
assert.equal(bytes[1], 0x4b);
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
const entries = new Map();
let pos = 0;
while (pos + 30 <= bytes.length && view.getUint32(pos, true) === 0x04034b50) {
const compMethod = view.getUint16(pos + 8, true);
assert.equal(compMethod, 0, 'ZIP STORE entry');
const compSize = view.getUint32(pos + 18, true);
const nameLen = view.getUint16(pos + 26, true);
const extraLen = view.getUint16(pos + 28, true);
const nameStart = pos + 30;
const dataStart = nameStart + nameLen + extraLen;
const name = Buffer.from(bytes.subarray(nameStart, nameStart + nameLen)).toString('utf8');
const text = Buffer.from(bytes.subarray(dataStart, dataStart + compSize)).toString('utf8');
entries.set(name, text);
pos = dataStart + compSize;
}
// Verify EOCD record exists at end
const eocdPos = bytes.length - 22;
assert.equal(view.getUint32(eocdPos, true), 0x06054b50, 'Valid ZIP EOCD signature');
assert.equal(view.getUint16(eocdPos + 10, true), entries.size);
return entries;
}
// 1. Formula injection neutralization and RFC-4180 quoting
assert.equal(escapeCsvCell('=CMD("calc")'), `"'=CMD(""calc"")"` );
assert.equal(escapeCsvCell('+SUM(A1:A2)'), `'+SUM(A1:A2)`);
@@ -1432,10 +1463,10 @@ test('Feature 11: RFC-4180 formula-safe CSV and Markdown report export for Steps
assert.equal(escapeCsvCell('-12.5'), '-12.5'); // genuine signed numbers preserved
assert.equal(escapeCsvCell('hello, "world"\nline2'), '"hello, ""world""\nline2"');
const fname = sanitizeExportFilename('my:bad/title*name?', 'csv', Date.UTC(2026, 10, 22, 8, 5));
assert.match(fname, /^my-bad-title-name-\d{8}-\d{4}\.csv$/);
const fname = sanitizeExportFilename('my:bad/title*name?', 'xlsx', Date.UTC(2026, 10, 22, 8, 5));
assert.match(fname, /^my-bad-title-name-\d{8}-\d{4}\.xlsx$/);
// 2. Steps CSV (UTF-8 BOM + safe cells) & Markdown report
// 2. Steps CSV, bilingual Markdown report, and native multi-sheet XLSX (with danger/info row styles)
const sampleSteps = [
{
stepIndex: 2,
@@ -1454,94 +1485,178 @@ test('Feature 11: RFC-4180 formula-safe CSV and Markdown report export for Steps
contextTokens: 100_500,
cacheHitPct: 90,
costUsd: 0.145,
anomaly: { count: 1, primaryKind: 'timeout', kinds: { timeout: 1 } },
turnPrompt: '=HYPERLINK("http://x"), "test"',
},
{
stepIndex: 3,
createdAtMs: Date.UTC(2026, 10, 22, 9, 5, 0),
modelShort: '4-neon',
modelLabel: 'Gemini 4 Neon',
inputTokens: 1_000,
cacheReadTokens: 50_000,
outputTokens: 300,
costUsd: 0.012,
isCompactionStep: true,
},
];
const stepsCsv = buildStepsCsv(sampleSteps);
assert.equal(stepsCsv.startsWith('\uFEFFstep,timestamp,'), true);
assert.match(stepsCsv, /"'=HYPERLINK\(""http:\/\/x""\), ""test"""/);
assert.match(stepsCsv, /0\.145000/);
const stepsMd = buildStepsMarkdownReport(sampleSteps, {
const stepsMdEn = buildStepsMarkdownReport(sampleSteps, {
title: 'Perf Audit',
cascadeId: 'cid-export-1',
locale: 'en-US',
});
assert.match(stepsMd, /# Perf Audit/);
assert.match(stepsMd, /## Model Breakdown/);
assert.match(stepsMd, /## Top Costliest Steps/);
assert.match(stepsMd, /#2/);
assert.match(stepsMdEn, /# Perf Audit/);
assert.match(stepsMdEn, /## Model Breakdown/);
assert.match(stepsMdEn, /## Top Costliest Steps/);
assert.match(stepsMdEn, /#2/);
// 3. Consumption CSV & Markdown report (including models + projects + sessions)
const stepsMdZh = buildStepsMarkdownReport(sampleSteps, {
title: 'Perf Audit',
cascadeId: 'cid-export-1',
locale: 'zh-CN',
});
assert.match(stepsMdZh, /## 模型分布/);
assert.match(stepsMdZh, /## 高成本步骤 Top 5/);
assert.match(stepsMdZh, /异常汇总/);
const stepsXlsxZh = parseZipStoreEntries(
buildStepsXlsx(sampleSteps, { title: 'Perf Audit', locale: 'zh-CN' })
);
assert.match(stepsXlsxZh.get('xl/workbook.xml'), /name="步骤明细"/);
assert.match(stepsXlsxZh.get('xl/workbook.xml'), /name="模型汇总"/);
const stepsSheetZh = stepsXlsxZh.get('xl/worksheets/sheet1.xml');
assert.match(stepsSheetZh, /<pane ySplit="1"/);
assert.match(stepsSheetZh, /<autoFilter ref="A1:R3"\/>/, 'AutoFilter excludes bottom summary row 4');
assert.match(stepsSheetZh, /t="inlineStr"[^>]*><is><t[^>]*>=HYPERLINK/, 'Formulas stored safely as inlineStr');
assert.match(stepsSheetZh, /自动压缩/);
assert.match(stepsSheetZh, /流空闲 \/ 连接超时/);
assert.match(stepsSheetZh, /合计(共 2 步)/);
const stepsXlsxEn = parseZipStoreEntries(
buildStepsXlsx(sampleSteps, { title: 'Perf Audit', locale: 'en-US' })
);
assert.match(stepsXlsxEn.get('xl/workbook.xml'), /name="Steps"/);
assert.match(stepsXlsxEn.get('xl/workbook.xml'), /name="Model Summary"/);
assert.match(stepsXlsxEn.get('xl/worksheets/sheet1.xml'), /Compaction/);
assert.match(stepsXlsxEn.get('xl/worksheets/sheet1.xml'), /Total \(2 steps\)/);
// 3. Consumption CSV, bilingual Markdown report, and 6-sheet native XLSX
const cons = {
selectedRange: { key: '7d', label: '近7天' },
selectedRange: { key: '7d', label: '近7天', startMs: Date.UTC(2026, 10, 15), endMs: Date.UTC(2026, 10, 22) },
account: {
calls: 12,
inputTokens: 100_000,
cacheReadTokens: 800_000,
outputTokens: 50_000,
totalTokens: 950_000,
cacheHitPct: 88.9,
costUsd: 2.35,
savedCostUsd: 1.45,
calls: 410,
inputTokens: 2_250_054,
cacheReadTokens: 100_300_000,
outputTokens: 479_037,
thinkingTokens: 136_100,
responseTokens: 342_937,
totalTokens: 103_029_091,
cacheHitPct: 97.8,
costUsd: 28.98,
savedCostUsd: 285.89,
},
topWorkspaces: [
{
label: 'usage-monitor',
workspacePath: 'F:/ppt/1111/antigravity-usage-monitor',
sessionCount: 3,
calls: 12,
inputTokens: 100_000,
cacheReadTokens: 800_000,
responseTokens: 30_000,
thinkingTokens: 20_000,
totalTokens: 950_000,
cacheHitPct: 88.9,
costUsd: 2.35,
calls: 333,
inputTokens: 1_859_526,
cacheReadTokens: 85_614_438,
responseTokens: 250_000,
thinkingTokens: 134_565,
totalTokens: 87_858_529,
cacheHitPct: 97.9,
costUsd: 24.1892,
},
],
topConversations: [
{
cascadeId: 'cid-1',
title: 'Refactor',
sourceName: 'CLI',
calls: 12,
inputTokens: 100_000,
cacheReadTokens: 800_000,
responseTokens: 30_000,
thinkingTokens: 20_000,
totalTokens: 950_000,
cacheHitPct: 88.9,
costUsd: 2.35,
sourceName: 'Antigravity App',
calls: 333,
inputTokens: 1_859_526,
cacheReadTokens: 85_614_438,
responseTokens: 250_000,
thinkingTokens: 134_565,
totalTokens: 87_858_529,
cacheHitPct: 97.9,
costUsd: 24.1892,
},
],
trendSeries: [
{ label: '11/22', fullLabel: '2026-11-22', calls: 12, tokens: 950_000, costUsd: 2.35 },
{ label: '11/22', fullLabel: '2026-11-22', granularity: 'day', calls: 410, inputTokens: 2_250_054, cacheReadTokens: 100_300_000, outputTokens: 479_037, tokens: 103_029_091, costUsd: 28.98 },
],
sourcesBreakdown: [
{ name: 'Antigravity App', calls: 333, inputTokens: 1_859_526, cacheReadTokens: 85_614_438, outputTokens: 384_565, totalTokens: 87_858_529, costUsd: 24.19 },
],
};
const models = [
{
label: '4-neon',
shortName: '4-neon',
calls: 12,
inputTokens: 100_000,
cacheReadTokens: 800_000,
outputTokens: 50_000,
totalTokens: 950_000,
cacheHitPct: 88.9,
avgTokPerSec: 52.1,
costUsd: 2.35,
calls: 410,
inputTokens: 2_250_054,
cacheReadTokens: 100_300_000,
outputTokens: 479_037,
totalTokens: 103_029_091,
cacheHitPct: 97.8,
avgTokPerSec: 50.9,
costUsd: 28.9826,
},
];
const consCsv = buildConsumptionCsv(cons, models);
assert.equal(consCsv.startsWith('\uFEFFsection,name,'), true);
assert.match(consCsv, /project,usage-monitor,12,/);
assert.match(consCsv, /trend,2026-11-22,12,/);
assert.match(consCsv, /project,usage-monitor,333,/);
assert.match(consCsv, /trend,2026-11-22,410,/);
const consMd = buildConsumptionMarkdownReport(cons, models);
assert.match(consMd, /# Usage Report · 近7天/);
assert.match(consMd, /## Models/);
assert.match(consMd, /## Projects/);
assert.match(consMd, /usage-monitor/);
assert.match(consMd, /## Top Sessions/);
const consMdEn = buildConsumptionMarkdownReport(cons, models, { locale: 'en-US' });
assert.match(consMdEn, /# Usage Report · Last 7 Days/);
assert.match(consMdEn, /## Models/);
assert.match(consMdEn, /## Projects/);
assert.match(consMdEn, /usage-monitor/);
assert.match(consMdEn, /## Top Sessions/);
const consMdZh = buildConsumptionMarkdownReport(cons, models, { locale: 'zh-CN' });
assert.match(consMdZh, /# 用量统计报告 · 近7天/);
assert.match(consMdZh, /## 模型排行/);
assert.match(consMdZh, /## 项目排行/);
assert.match(consMdZh, /## 热门会话/);
const consXlsxZh = parseZipStoreEntries(buildConsumptionXlsx(cons, models, { locale: 'zh-CN' }));
const wbZh = consXlsxZh.get('xl/workbook.xml');
for (const sheetName of ['用量总览', '模型排行', '项目排行', '会话排行', '时间趋势', '客户端来源']) {
assert.ok(wbZh.includes(`name="${sheetName}"`), `ZH workbook includes sheet ${sheetName}`);
}
const stylesXml = consXlsxZh.get('xl/styles.xml');
assert.match(stylesXml, /formatCode="#,##0"/);
assert.match(stylesXml, /formatCode="\$#,##0\.00"/);
assert.match(stylesXml, /formatCode="0\.0%"/);
assert.match(stylesXml, /<cellXfs count="45">/);
const modelsSheetZh = consXlsxZh.get('xl/worksheets/sheet2.xml');
assert.match(modelsSheetZh, /<v>103029091<\/v>/, 'Large token count stored as raw integer without scientific notation');
assert.match(modelsSheetZh, /customWidth="1"/, 'Auto column widths emitted');
assert.match(modelsSheetZh, /<autoFilter ref="A1:J2"\/>/, 'Models autoFilter excludes bottom total row');
const consXlsxEn = parseZipStoreEntries(buildConsumptionXlsx(cons, models, { locale: 'en-US' }));
const wbEn = consXlsxEn.get('xl/workbook.xml');
for (const sheetName of ['Overview', 'Models', 'Projects', 'Sessions', 'Trend', 'Client Sources']) {
assert.ok(wbEn.includes(`name="${sheetName}"`), `EN workbook includes sheet ${sheetName}`);
}
assert.match(consXlsxEn.get('xl/worksheets/sheet1.xml'), /Last 7 Days/);
assert.equal(consXlsxEn.get('xl/worksheets/sheet1.xml').includes('近7天'), false);
assert.equal(buildConsumptionExportBaseName(cons, '7d', { locale: 'zh-CN' }), '用量统计-近7天');
assert.equal(buildConsumptionExportBaseName(cons, '7d', { locale: 'en-US' }), 'usage-7d');
assert.equal(buildStepsExportBaseName('调试任务', '', { locale: 'zh-CN' }), '调用明细-调试任务');
assert.equal(buildStepsExportBaseName('Debug Task', '', { locale: 'en-US' }), 'steps-Debug Task');
});
test('Feature 13: TopSessionHeader exposes project/workspace tags on sessions and filters by workspace name', async (t) => {
@@ -1679,6 +1794,38 @@ test('Feature 14: compact vertical ActionMenu replaces export bars, backend expo
assert.equal(exp2.ok, true);
assert.equal(exp2.fileName, 'usage-today (1).csv');
// Binary .xlsx base64 export writes exact ZIP/PK archive and rejects corrupted non-PK payload
const { buildXlsxWorkbookBytes, uint8ArrayToBase64 } = await import('../src/core/xlsxBuilder.js');
const miniXlsx = buildXlsxWorkbookBytes([
{ name: '总览', columns: [{ header: '指标', type: 'text' }], rows: [['测试']] },
]);
const expXlsx = writeLocalExportFile(
{
filename: '用量统计-今日.xlsx',
content: uint8ArrayToBase64(miniXlsx),
encoding: 'base64',
mimeType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
},
{ overrideDir: tempExportDir }
);
assert.equal(expXlsx.ok, true);
assert.equal(expXlsx.fileName, '用量统计-今日.xlsx');
const savedXlsxBytes = readFileSync(expXlsx.filePath);
assert.equal(savedXlsxBytes[0], 0x50);
assert.equal(savedXlsxBytes[1], 0x4b);
assert.equal(savedXlsxBytes.length, miniXlsx.length);
const badXlsx = writeLocalExportFile(
{
filename: 'corrupt.xlsx',
content: Buffer.from('not-a-zip').toString('base64'),
encoding: 'base64',
},
{ overrideDir: tempExportDir }
);
assert.equal(badXlsx.ok, false);
assert.equal(badXlsx.status, 400);
// Unauthorized arbitrary path must be rejected (403)
const denied = revealLocalExportFile(path.join(tempExportDir, 'not-exported.txt'), {
platform: 'win32',
@@ -1762,7 +1909,7 @@ test('Feature 14: compact vertical ActionMenu replaces export bars, backend expo
ok: true,
filePath: apiSaveBody.filePath,
dirPath: tempExportDir,
fileName: 'usage-7d.csv',
fileName: parsedBody.filename || '用量统计-近7天.xlsx',
}),
};
}
@@ -1839,15 +1986,20 @@ test('Feature 14: compact vertical ActionMenu replaces export bars, backend expo
menu.refs.triggerBtn.dispatchEvent({ type: 'click', stopPropagation: () => {} });
assert.equal(menu.refs.isOpen(), true);
const csvItem = menu.refs.getItemBtn('csv');
assert.ok(csvItem);
csvItem.dispatchEvent({ type: 'click', stopPropagation: () => {} });
const xlsxItem = menu.refs.getItemBtn('xlsx');
assert.ok(xlsxItem);
xlsxItem.dispatchEvent({ type: 'click', stopPropagation: () => {} });
assert.equal(menu.refs.isOpen(), false);
await new Promise((r) => setTimeout(r, 15));
const exportCall = apiCalls.find((c) => String(c.url).includes('/api/export-file'));
assert.ok(exportCall, 'XLSX menu item posts to /api/export-file');
assert.equal(exportCall.body.encoding, 'base64');
assert.match(exportCall.body.filename, /^用量统计-近7天-\d{8}-\d{4}\.xlsx$/);
const toast = uiStore.getState().toast;
assert.ok(toast, 'Export displays global toast');
assert.match(toast.message, /usage-7d\.csv/);
assert.match(toast.message, /用量统计-近7天-.*\.xlsx/);
assert.equal(toast.detail, apiSaveBody.filePath);
assert.equal(toast.actionLabel, '打开位置');
assert.equal(typeof toast.onAction, 'function');