spreadsheet.ts 5.13 KB
// 电子表格(xlsx/xls)解析为 x-data-spreadsheet 可渲染的数据结构。
// 纯计算逻辑,从 app/page.tsx 抽出。

import * as XLSX from "xlsx";
import type { SheetData } from "x-data-spreadsheet";

export const SPREADSHEET_MAX_ROWS = 5000;
export const SPREADSHEET_MAX_CELLS = 200000;
export const SPREADSHEET_MAX_FILE_BYTES = 50 * 1024 * 1024;

const FONT_UNIT_PX = 7;
const CELL_PADDING_PX = 16;
const MIN_COL_WIDTH = 50;
const MAX_AUTO_COL_WIDTH = 320;
const DEFAULT_ROW_HEIGHT = 25;
const ROW_LINE_HEIGHT = 20;

const colWidthFromExcel = (col?: { wch?: number; wpx?: number }) => {
  if (!col) return undefined;
  if (typeof col.wpx === "number") return col.wpx;
  if (typeof col.wch === "number") return Math.round(col.wch * 7 + 5);
  return undefined;
};

const isWideChar = (code: number) => (
  (code >= 0x1100 && code <= 0x115f)
  || (code >= 0x2e80 && code <= 0xa4cf && code !== 0x303f)
  || (code >= 0xac00 && code <= 0xd7a3)
  || (code >= 0xf900 && code <= 0xfaff)
  || (code >= 0xff00 && code <= 0xff60)
  || (code >= 0xffe0 && code <= 0xffe6)
);

const textDisplayUnits = (text: string) => {
  let units = 0;
  for (const ch of text) {
    units += isWideChar(ch.codePointAt(0) || 0) ? 2 : 1;
  }
  return units;
};

export const workbookToSpreadsheetData = (
  workbook: import("xlsx").WorkBook
): { sheets: SheetData[]; truncated: boolean } => {
  let truncated = false;

  const sheets: SheetData[] = workbook.SheetNames.map((name) => {
    const worksheet = workbook.Sheets[name];
    const ref = worksheet["!ref"];
    const rows: Record<number, { cells: Record<number, { text: string; style?: number }>; height?: number }> & { len?: number } = {};
    const cols: Record<number, { width: number }> & { len?: number } = {};
    const colMaxUnits: Record<number, number> = {};

    if (ref) {
      const range = XLSX.utils.decode_range(ref);
      let maxRow = range.e.r;
      const totalCols = range.e.c - range.s.c + 1;
      const rowLimit = Math.max(
        0,
        Math.min(maxRow - range.s.r, SPREADSHEET_MAX_ROWS - 1, Math.floor(SPREADSHEET_MAX_CELLS / Math.max(totalCols, 1)) - 1)
      );
      if (range.e.r - range.s.r > rowLimit) {
        truncated = true;
        maxRow = range.s.r + rowLimit;
      }

      for (let r = range.s.r; r <= maxRow; r++) {
        const cells: Record<number, { text: string; style?: number }> = {};
        let hasValue = false;
        for (let c = range.s.c; c <= range.e.c; c++) {
          const cellAddr = XLSX.utils.encode_cell({ r, c });
          const cell = worksheet[cellAddr];
          if (cell && cell.v !== undefined && cell.v !== null) {
            const text = String(cell.v);
            cells[c - range.s.c] = { text };
            hasValue = true;
            const col = c - range.s.c;
            const lineUnits = Math.max(...text.split("\n").map(textDisplayUnits));
            colMaxUnits[col] = Math.max(colMaxUnits[col] || 0, lineUnits);
          }
        }
        if (hasValue) {
          rows[r - range.s.r] = { cells };
        }
      }
      rows.len = maxRow - range.s.r + 1;
      cols.len = totalCols;
    }

    const excelCols = (worksheet["!cols"] || []) as Array<{ wch?: number; wpx?: number } | undefined>;
    for (let c = 0; c < (cols.len || 0); c++) {
      const autoWidth = Math.min(
        MAX_AUTO_COL_WIDTH,
        Math.max(MIN_COL_WIDTH, (colMaxUnits[c] || 0) * FONT_UNIT_PX + CELL_PADDING_PX)
      );
      const storedWidth = colWidthFromExcel(excelCols[c]);
      const width = Math.max(autoWidth, storedWidth || 0);
      if (width) {
        cols[c] = { width };
      }
    }

    const wrapStyleIndex = 0;
    Object.keys(rows).forEach((rowKey) => {
      if (rowKey === "len") return;
      const row = rows[Number(rowKey)];
      let neededHeight = DEFAULT_ROW_HEIGHT;
      Object.keys(row.cells).forEach((colKey) => {
        const c = Number(colKey);
        const cellData = row.cells[c];
        const colWidth = cols[c]?.width || MIN_COL_WIDTH;
        const capacityUnits = Math.max(1, Math.floor((colWidth - CELL_PADDING_PX) / FONT_UNIT_PX));
        const segments = cellData.text.split("\n");
        const totalLines = segments.reduce(
          (sum, seg) => sum + Math.max(1, Math.ceil(textDisplayUnits(seg) / capacityUnits)),
          0
        );
        if (totalLines > 1) {
          cellData.style = wrapStyleIndex;
          neededHeight = Math.max(neededHeight, totalLines * ROW_LINE_HEIGHT + 8);
        }
      });
      if (neededHeight > DEFAULT_ROW_HEIGHT) {
        row.height = neededHeight;
      }
    });

    const merges = ((worksheet["!merges"] || []) as Array<{ s: { r: number; c: number }; e: { r: number; c: number } }>)
      .filter((m) => ref && m.e.r < (XLSX.utils.decode_range(ref).s.r + (rows.len || 0)))
      .map((m) => {
        const base = ref ? XLSX.utils.decode_range(ref) : { s: { r: 0, c: 0 } };
        return `${XLSX.utils.encode_cell({ r: m.s.r - base.s.r, c: m.s.c - base.s.c })}:${XLSX.utils.encode_cell({ r: m.e.r - base.s.r, c: m.e.c - base.s.c })}`;
      });

    return {
      name,
      rows,
      cols,
      merges,
      styles: [{ textwrap: true, valign: "top" }],
    } as SheetData;
  });

  return { sheets, truncated };
};