excel-store.ts 8.53 KB
/**
 * Excel 读写:把表格抽成文本矩阵交给补齐逻辑,写回时整行搬移原单元格对象,
 * 因此未改动的列保持原有类型与显示格式(数值仍是数值,日期仍按原格式显示)。
 */
import fs from 'node:fs';
import path from 'node:path';
import XLSX from 'xlsx';
import type { CellObject, ColInfo, NumberFormat, RowInfo, WorkBook, WorkSheet } from 'xlsx';
import { UserError } from './errors.ts';
import { COORDINATE_COLUMNS } from './targets.ts';
import { atomicWrite } from './csv-store.ts';

export const EXCEL_SUFFIXES = ['.xlsx', '.xlsm', '.xlsb', '.xls'];

export type ExcelSheet = {
  workbook: WorkBook;
  sheetName: string;
  headerRow: number;
  columnCount: number;
  width: number;
  headerCells: (CellObject | undefined)[];
  cells: (CellObject | undefined)[][];
  rowNumbers: number[];
  cols: ColInfo[] | null;
  rowHeights: RowInfo[] | null;
};

export type ExcelTable = { header: string[]; rows: string[][]; sheet: ExcelSheet };

export function isExcel(file: string): boolean {
  return EXCEL_SUFFIXES.includes(path.extname(file).toLowerCase());
}

/** 带日期/时间显示格式的数字单元格取显示文本,其余数字取原值,不裁剪坐标有效数字。 */
function isDateFormat(format: NumberFormat | undefined): boolean {
  if (format === undefined) return false;
  // 内置格式在文件里可能只存序号,需要先查格式表再判断是否为日期。
  const pattern = typeof format === 'number'
    ? XLSX.SSF.get_table()[format] as string | undefined
    : format;
  return pattern !== undefined && pattern !== '' && pattern !== 'General'
    && XLSX.SSF.is_date(pattern);
}

export function cellText(cell: CellObject | undefined): string {
  if (cell === undefined) return '';
  if (cell.v === undefined) return cell.w ?? '';
  if (cell.t === 'b') return cell.v ? 'TRUE' : 'FALSE';
  if (cell.t === 'd' || cell.t === 'e') return cell.w ?? String(cell.v);
  if (cell.t === 'n' && isDateFormat(cell.z)) return cell.w ?? String(cell.v);
  return String(cell.v);
}

function readWorkbook(file: string): WorkBook {
  const body = fs.readFileSync(file);
  const zip = body[0] === 0x50 && body[1] === 0x4b;
  const legacy = body[0] === 0xd0 && body[1] === 0xcf && body[2] === 0x11 && body[3] === 0xe0;
  if (body.length === 0 || !(zip || legacy)) {
    throw new UserError('文件不是有效的 Excel 工作簿;文本表格请直接把扩展名写成 .csv');
  }
  try {
    return XLSX.read(body, { type: 'buffer', cellNF: true, cellStyles: true });
  } catch (exc) {
    // 保留底层原因,否则损坏文件与依赖异常都只剩同一句话,无法排查。
    const reason = (exc instanceof Error ? exc.message : String(exc)).slice(0, 120);
    throw new UserError(`无法读取 Excel 文件(${reason}),请确认文件未损坏、未加密且未被 Excel 独占`);
  }
}

/** 取第一个工作表;表尾全空行忽略,数据超出表头宽度时要求先补表头名称。 */
export function readExcel(file: string, limit: number | null): ExcelTable {
  const workbook = readWorkbook(path.resolve(file));
  const sheetName = workbook.SheetNames[0];
  const sheet = sheetName === undefined ? undefined : workbook.Sheets[sheetName];
  const reference = sheet?.['!ref'];
  if (sheet === undefined || sheetName === undefined || reference === undefined) {
    throw new UserError('Excel 中没有可读的工作表');
  }
  const range = XLSX.utils.decode_range(reference);
  const at = (row: number, column: number) => sheet[XLSX.utils.encode_cell({ r: row, c: column })];
  const columns = range.e.c - range.s.c + 1;
  const names: string[] = [];
  for (let column = 0; column < columns; column += 1) {
    names.push(cellText(at(range.s.r, range.s.c + column)));
  }
  let width = names.length;
  while (width > 0 && names[width - 1] === '') width -= 1;
  if (width === 0) throw new UserError('Excel 表头为空');
  const header = names.slice(0, width);
  if (new Set(header).size !== header.length) throw new UserError('Excel 表头含重名列');
  if (COORDINATE_COLUMNS.some((name) => !header.includes(name))) {
    throw new UserError('Excel 必须包含经度、纬度列');
  }

  const texts: string[][] = [];
  const cells: (CellObject | undefined)[][] = [];
  const rowNumbers: number[] = [];
  for (let row = range.s.r + 1; row <= range.e.r; row += 1) {
    const rowCells: (CellObject | undefined)[] = [];
    for (let column = 0; column < columns; column += 1) {
      rowCells.push(at(row, range.s.c + column));
    }
    if (rowCells.slice(width).some((cell) => cellText(cell) !== '')) {
      throw new UserError(`${XLSX.utils.encode_col(range.s.c + width)} 列及之后有数据但缺少表头名称,请先补全表头`);
    }
    texts.push(header.map((_, column) => cellText(rowCells[column])));
    cells.push(rowCells);
    rowNumbers.push(row);
  }
  const blankRow = (rowCells: (CellObject | undefined)[]) => rowCells.every((cell) => cellText(cell) === '');
  while (texts.length > 0 && blankRow(cells[cells.length - 1])) {
    texts.pop();
    cells.pop();
    rowNumbers.pop();
  }
  if (limit !== null) {
    texts.length = Math.min(texts.length, limit);
    cells.length = texts.length;
    rowNumbers.length = texts.length;
  }
  return {
    header,
    rows: texts,
    sheet: {
      workbook,
      sheetName,
      headerRow: range.s.r,
      columnCount: columns,
      width,
      headerCells: Array.from({ length: columns }, (_, column) => at(range.s.r, range.s.c + column)),
      cells,
      rowNumbers,
      cols: sheet['!cols'] ?? null,
      rowHeights: sheet['!rows'] ?? null,
    },
  };
}

/** CSV 之类没有单元格元数据的来源改写成 Excel 时使用;全部值按文本落格。 */
export function blankSheet(header: readonly string[], rows: readonly string[][]): ExcelSheet {
  const sheetName = '数据';
  const workbook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(workbook, { '!ref': 'A1' }, sheetName);
  return {
    workbook,
    sheetName,
    headerRow: 0,
    columnCount: header.length,
    width: header.length,
    headerCells: [],
    cells: rows.map(() => []),
    rowNumbers: rows.map((_, index) => index + 1),
    cols: null,
    rowHeights: null,
  };
}

/** 新值一律写成文本单元格;原单元格有样式时沿用,避免补出来的列风格突变。 */
function textCell(value: string, original: CellObject | undefined): CellObject | undefined {
  if (value === '') return undefined;
  const cell: CellObject = { t: 's', v: value };
  if (original?.s !== undefined) cell.s = original.s;
  return cell;
}

/** 按当前行序重建工作表:逐格比较文本,未变动的格子搬回原单元格对象。 */
export function writeExcel(file: string, header: readonly string[], rows: readonly string[][],
  sheet: ExcelSheet): void {
  const target = path.resolve(file);
  const extension = path.extname(target).toLowerCase();
  if (extension !== '.xlsx' && extension !== '.xlsm') {
    throw new UserError('Excel 输出仅支持 .xlsx 或 .xlsm');
  }
  const rebuilt: WorkSheet = {};
  const put = (row: number, column: number, cell: CellObject | undefined): void => {
    if (cell !== undefined) rebuilt[XLSX.utils.encode_cell({ r: row, c: column })] = cell;
  };
  const headerColumns = Math.max(sheet.headerCells.length, header.length);
  for (let column = 0; column < headerColumns; column += 1) {
    const cell = sheet.headerCells[column];
    const value = column < header.length ? header[column] : cellText(cell);
    put(0, column, cellText(cell) === value ? cell : textCell(value, cell));
  }
  rows.forEach((row, index) => {
    const originals = sheet.cells[index] ?? [];
    const columns = Math.max(originals.length, row.length);
    for (let column = 0; column < columns; column += 1) {
      const cell = originals[column];
      const value = column < row.length ? row[column] : cellText(cell);
      put(index + 1, column, cellText(cell) === value ? cell : textCell(value, cell));
    }
  });
  const columns = Math.max(sheet.columnCount, header.length);
  rebuilt['!ref'] = XLSX.utils.encode_range({
    s: { r: 0, c: 0 }, e: { r: rows.length, c: columns - 1 },
  });
  if (sheet.cols !== null) rebuilt['!cols'] = sheet.cols;
  if (sheet.rowHeights !== null) {
    const heights = sheet.rowHeights;
    rebuilt['!rows'] = [heights[sheet.headerRow],
      ...sheet.rowNumbers.map((row) => heights[row])];
  }
  sheet.workbook.Sheets[sheet.sheetName] = rebuilt;
  const body = XLSX.write(sheet.workbook, {
    bookType: extension === '.xlsm' ? 'xlsm' : 'xlsx',
    type: 'buffer',
    cellStyles: true,
    compression: true,
  }) as Uint8Array;
  atomicWrite(target, body);
}