Toolpal

@toolpal/markdown-to-doc

public

v2.0published 1 download this weekMIT

Converts Markdown (inline or .md/.txt file) or structured JSON/sheets locally into a formatted Word (.docx), PDF (.pdf), or Excel (.xlsx) file. Supports headings, bold/italic/code, links, lists, code blocks, blockquotes, and tables. Offline, no API key needed.

src/xlsx.ts5.5 KBRaw
// Zero-dependency .xlsx workbook writer with bold frozen headers, typed cells & auto widths.
import { Buffer } from "node:buffer";
import { escapeXml as esc, zip } from "./zip.js";

export type Cell = string | number | boolean | null | undefined;

export interface Sheet {
  name: string;
  header: string[];
  rows: Cell[][];
}

const NS = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";
const R = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
const REL = "http://schemas.openxmlformats.org/package/2006/relationships";
const XML_HEAD = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n';

function columnName(index: number): string {
  let name = "";
  let n = index;
  do {
    name = String.fromCharCode(65 + (n % 26)) + name;
    n = Math.floor(n / 26) - 1;
  } while (n >= 0);
  return name;
}

function sheetName(name: string): string {
  return name.replace(/[[\]:*?/\\]/g, " ").trim().slice(0, 31) || "Sheet";
}

function cellXml(ref: string, value: Cell, bold: boolean): string {
  const s = bold ? ' s="1"' : "";
  if (value === null || value === undefined) return "";
  if (typeof value === "number") {
    return Number.isFinite(value) ? `<c r="${ref}"${s}><v>${value}</v></c>` : "";
  }
  if (typeof value === "boolean") return `<c r="${ref}"${s} t="b"><v>${value ? 1 : 0}</v></c>`;
  return `<c r="${ref}"${s} t="inlineStr"><is><t xml:space="preserve">${esc(value)}</t></is></c>`;
}

function sheetXml(sheet: Sheet): string {
  const colCount = Math.max(sheet.header.length, ...sheet.rows.map((r) => r.length), 1);
  const widths = Array.from({ length: colCount }, (_, c) =>
    Math.min(
      60,
      Math.max(
        10,
        (sheet.header[c] ?? "").length + 2,
        ...sheet.rows.slice(0, 200).map((r) => String(r[c] ?? "").length + 2),
      ),
    ),
  );
  const cols = `<cols>${widths.map((w, c) => `<col min="${c + 1}" max="${c + 1}" width="${w}" customWidth="1"/>`).join("")}</cols>`;
  const allRows: Cell[][] = sheet.header.length > 0 ? [sheet.header, ...sheet.rows] : sheet.rows;
  const rowsXml = allRows
    .map(
      (cells, r) =>
        `<row r="${r + 1}">${cells.map((v, c) => cellXml(`${columnName(c)}${r + 1}`, v, r === 0 && sheet.header.length > 0)).join("")}</row>`,
    )
    .join("");
  const freeze =
    sheet.header.length > 0
      ? '<pane ySplit="1" topLeftCell="A2" activePane="bottomLeft" state="frozen"/>'
      : "";
  return `${XML_HEAD}<worksheet xmlns="${NS}" xmlns:r="${R}"><sheetViews><sheetView workbookViewId="0">${freeze}</sheetView></sheetViews><sheetFormatPr defaultRowHeight="15"/>${cols}<sheetData>${rowsXml}</sheetData></worksheet>`;
}

export function renderXlsx(sheets: Sheet[]): Buffer {
  if (sheets.length === 0) throw new Error("A workbook needs at least one sheet.");
  const names = new Set<string>();
  const unique = sheets.map((s) => {
    let name = sheetName(s.name);
    let n = 2;
    while (names.has(name)) name = `${sheetName(s.name).slice(0, 28)} ${n++}`;
    names.add(name);
    return name;
  });
  const workbook = `${XML_HEAD}<workbook xmlns="${NS}" xmlns:r="${R}"><sheets>${unique.map((name, i) => `<sheet name="${esc(name)}" sheetId="${i + 1}" r:id="rId${i + 1}"/>`).join("")}</sheets></workbook>`;
  const workbookRels = `${XML_HEAD}<Relationships xmlns="${REL}">${sheets.map((_, i) => `<Relationship Id="rId${i + 1}" Type="${R}/worksheet" Target="worksheets/sheet${i + 1}.xml"/>`).join("")}<Relationship Id="rIdStyles" Type="${R}/styles" Target="styles.xml"/></Relationships>`;
  const styles = `${XML_HEAD}<styleSheet xmlns="${NS}"><fonts count="2"><font><sz val="11"/><name val="Calibri"/></font><font><b/><sz val="11"/><name val="Calibri"/></font></fonts><fills count="2"><fill><patternFill patternType="none"/></fill><fill><patternFill patternType="gray125"/></fill></fills><borders count="1"><border><left/><right/><top/><bottom/><diagonal/></border></borders><cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs><cellXfs count="2"><xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/><xf numFmtId="0" fontId="1" fillId="0" borderId="0" xfId="0" applyFont="1"/></cellXfs><cellStyles count="1"><cellStyle name="Normal" xfId="0" builtinId="0"/></cellStyles></styleSheet>`;
  const rootRels = `${XML_HEAD}<Relationships xmlns="${REL}"><Relationship Id="rId1" Type="${R}/officeDocument" Target="xl/workbook.xml"/></Relationships>`;
  const contentTypes = `${XML_HEAD}<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"/><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"/>${sheets.map((_, i) => `<Override PartName="/xl/worksheets/sheet${i + 1}.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>`).join("")}</Types>`;
  return zip([
    { name: "[Content_Types].xml", data: Buffer.from(contentTypes) },
    { name: "_rels/.rels", data: Buffer.from(rootRels) },
    { name: "xl/workbook.xml", data: Buffer.from(workbook) },
    { name: "xl/_rels/workbook.xml.rels", data: Buffer.from(workbookRels) },
    { name: "xl/styles.xml", data: Buffer.from(styles) },
    ...sheets.map((s, i) => ({
      name: `xl/worksheets/sheet${i + 1}.xml`,
      data: Buffer.from(sheetXml(s)),
    })),
  ]);
}