Files
monkey-ai-web/src/helpers/exportCsv.js
T
2026-10-15 16:33:46 +08:00

76 lines
2.6 KiB
JavaScript

/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
// 导出当前页日志为 CSV,只在前端处理,不新增后端接口
// 作用域:仅当前页(rows 是已加载到内存的列表)。如需全量导出,后续可接后端 stream 接口
// 用 \uFEFF BOM 让 Excel 自动识别 UTF-8;字段值里遇到 "、,、换行 的用双引号包裹并转义
const escapeCsvCell = (value) => {
if (value === null || value === undefined) return '';
const s = String(value);
if (
s.includes('"') ||
s.includes(',') ||
s.includes('\n') ||
s.includes('\r')
) {
return '"' + s.replace(/"/g, '""') + '"';
}
return s;
};
/**
* @param {Array<{key: string, title: string, format?: (row:any)=>string}>} columns
* @param {Array<Object>} rows
* @param {string} filename
*/
export const exportToCsv = (columns, rows, filename) => {
const header = columns.map((c) => escapeCsvCell(c.title)).join(',');
const body = rows
.map((row) =>
columns
.map((c) => {
const raw =
typeof c.format === 'function' ? c.format(row) : row[c.key];
return escapeCsvCell(raw);
})
.join(','),
)
.join('\n');
const csv = '\uFEFF' + header + '\n' + body;
const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
};
// 把秒级时间戳格式化为 CSV 友好的 YYYY-MM-DD HH:mm:ss,空值回落为空串
export const formatTimestampForCsv = (sec) => {
if (!sec) return '';
const d = new Date(sec * 1000);
const pad = (n) => ('0' + n).slice(-2);
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
};