# 表格转 Markdown

> 把从电子表格复制的表格或 CSV 转为 Markdown 表格，首行作为表头

版本：1.0.0 · 作者 Deck

- 安装到 Deck：deck://install-plugin?id=table-to-markdown&url=https%3A%2F%2Fgithub.com%2Fyuzeguitarist%2Fdeck-plugins%2Freleases%2Fdownload%2Fplugins%2Ftable-to-markdown-1.0.0.zip
- 下载 .zip：https://github.com/yuzeguitarist/deck-plugins/releases/download/plugins/table-to-markdown-1.0.0.zip
- 在 GitHub 上查看：https://github.com/yuzeguitarist/deck-plugins/tree/main/plugins/table-to-markdown

也可以用终端安装：

```sh
mkdir -p ~/.deck/scripts/table-to-markdown && curl -fsSL https://github.com/yuzeguitarist/deck-plugins/releases/download/plugins/table-to-markdown-1.0.0.zip | tar -xf - -C ~/.deck/scripts/table-to-markdown
```

## 脚本

```js
// Turns a table copied from a spreadsheet (tab-separated) or CSV into a Markdown table whose first row is the header.
function parseRows(text, delimiter) {
  const rows = [];
  let row = [];
  let i = 0;
  for (;;) {
    let value = null;
    if (text[i] === '"') {
      // A quoted field: "" stands for a quote, and the closing quote must end the field.
      const pieces = [];
      let j = i + 1;
      for (;;) {
        const quote = text.indexOf('"', j);
        if (quote === -1) break;
        pieces.push(text.slice(j, quote));
        if (text[quote + 1] === '"') {
          pieces.push('"');
          j = quote + 2;
          continue;
        }
        const next = text[quote + 1];
        if (next === undefined || next === delimiter || next === "\n" || next === "\r") {
          value = pieces.join("");
          i = quote + 1;
        }
        break;
      }
    }
    if (value === null) {
      let j = i;
      while (j < text.length && text[j] !== delimiter && text[j] !== "\n" && text[j] !== "\r") j += 1;
      value = text.slice(i, j);
      i = j;
    }
    row.push(value);
    if (i >= text.length) break;
    if (text[i] === delimiter) {
      i += 1;
    } else {
      i += text[i] === "\r" && text[i + 1] === "\n" ? 2 : 1;
      rows.push(row);
      row = [];
    }
  }
  rows.push(row);
  return rows;
}

function cell(value) {
  return value.trim().replace(/\|/g, "\\|").replace(/\r\n|\r|\n/g, "<br>");
}

function transform(input) {
  const text = String(input ?? "");
  let end = text.length;
  while (end > 0 && (text[end - 1] === "\n" || text[end - 1] === "\r")) end -= 1;
  const body = text.slice(0, end);
  const rows = parseRows(body, body.indexOf("\t") !== -1 ? "\t" : ",");
  const columns = rows[0].length;
  if (rows.length < 2 || columns < 2 || rows.some((row) => row.length !== columns)) return text;
  const lines = rows.map((row) => "| " + row.map(cell).join(" | ") + " |");
  lines.splice(1, 0, "|" + " --- |".repeat(columns));
  return lines.join("\n");
}
```

---

- HTML：https://deckclip.app/zh-cn/plugins/table-to-markdown
- English：https://deckclip.app/plugins/table-to-markdown.md

© 2026 潘禹泽
