Skip to main content

使用 ParcelJS 打包工作表

ParcelJS 是一个模块打包器。

¥ParcelJS is a module bundler.

SheetJS 是一个用于从电子表格读取和写入数据的 JavaScript 库。

¥SheetJS is a JavaScript library for reading and writing data from spreadsheets.

本演示使用 ParcelJS 和 SheetJS 导出数据。我们将探讨如何使用 ParcelJS 将 SheetJS 打包到站点中,以及如何将数据导出到电子表格。

¥This demo uses ParcelJS and SheetJS to export data. We'll explore how to bundle SheetJS in a site using ParcelJS and how to export data to spreadsheets.

该演示重点介绍与 ParcelJS 打包器的集成细节。

¥This demo focuses on integration details with the ParcelJS bundler.

这些演示遵循 "导出教程",其中更详细地介绍了 SheetJS 库的用法。

¥The demos follow the "Export Tutorial", which covers SheetJS library usage in more detail.

测试部署

本 demo 在以下环境下进行了测试:

¥This demo was tested in the following environments:

版本日期
2.12.02024-06-08
1.12.42024-06-08

集成详情

¥Integration Details

"构架" 章节 涵盖了 Yarn 和其他包管理器的安装。

¥The "Frameworks" section covers installation with Yarn and other package managers.

在 RollupJS 项目中安装 SheetJS 模块后,import 语句可以加载库的相关部分:

¥After installing the SheetJS module in a RollupJS project, import statements can load relevant parts of the library:

import { read, utils, writeFileXLSX } from 'xlsx';
Parcel 缺陷

Could not statically evaluate fs call 形式的错误源自 Parcel bug[^1]。升级到 Parcel 版本 1.5.0 或更高版本。

¥Errors of the form Could not statically evaluate fs call stem from a Parcel bug[^1]. Upgrade to Parcel version 1.5.0 or later.

完整示例

¥Complete Example

该演示遵循 导出示例

¥This demo follows the Export Example.

  1. 初始化一个新项目:

    ¥Initialize a new project:

mkdir sheetjs-parceljs
cd sheetjs-parceljs
npm init -y
  1. 将以下内容保存到 index.html

    ¥Save the following to index.html:

index.html
<body>
<h3>SheetJS <span id="vers"></span> export demo</h3>
<button id="xport">Click to Export!</button>
<!-- the script tag must be marked as `type="module"` -->
<script type="module">
// ESM-style import from "xlsx"
import { utils, version, writeFileXLSX } from 'xlsx';

document.getElementById("vers").innerText = version;
document.getElementById("xport").onclick = async() => {
/* fetch JSON data and parse */
const url = "https://xlsx.nodejs.cn/executive.json";
const raw_data = await (await fetch(url)).json();

/* filter for the Presidents */
const prez = raw_data.filter(row => row.terms.some(term => term.type === "prez"));

/* sort by first presidential term */
prez.forEach(row => row.start = row.terms.find(term => term.type === "prez").start);
prez.sort((l,r) => l.start.localeCompare(r.start));

/* flatten objects */
const rows = prez.map(row => ({
name: row.name.first + " " + row.name.last,
birthday: row.bio.birthday
}));

/* generate worksheet and workbook */
const worksheet = utils.json_to_sheet(rows);
const workbook = utils.book_new();
utils.book_append_sheet(workbook, worksheet, "Dates");

/* fix headers */
utils.sheet_add_aoa(worksheet, [["Name", "Birthday"]], { origin: "A1" });

/* calculate column width */
const max_width = rows.reduce((w, r) => Math.max(w, r.name.length), 10);
worksheet["!cols"] = [ { wch: max_width } ];

/* create an XLSX file and try to save to Presidents.xlsx */
writeFileXLSX(workbook, "Presidents.xlsx");
};
</script>
<body>

ParcelJS v1 不支持内联脚本中的 import 语句。

¥ParcelJS v1 did not support import statements within inline scripts.

对于 ParcelJS 版本 1,整个脚本应复制到 index.js,并且 index.html 主页面应加载 index.js 脚本:

¥For ParcelJS version 1, the entire script should be copied to index.js and the main index.html page should load the index.js script:

ParcelJS v1 example (click to show)
index.html
<body>
<h3>SheetJS <span id="vers"></span> export demo</h3>
<button id="xport">Click to Export!</button>
<script src="index.js" type="module"></script>
<body>
index.js
// ESM-style import from "xlsx"
import { utils, version, writeFileXLSX } from 'xlsx';

document.getElementById("vers").innerText = version;
document.getElementById("xport").onclick = async() => {
/* fetch JSON data and parse */
const url = "https://xlsx.nodejs.cn/executive.json";
const raw_data = await (await fetch(url)).json();

/* filter for the Presidents */
const prez = raw_data.filter(row => row.terms.some(term => term.type === "prez"));

/* sort by first presidential term */
prez.forEach(row => row.start = row.terms.find(term => term.type === "prez").start);
prez.sort((l,r) => l.start.localeCompare(r.start));

/* flatten objects */
const rows = prez.map(row => ({
name: row.name.first + " " + row.name.last,
birthday: row.bio.birthday
}));

/* generate worksheet and workbook */
const worksheet = utils.json_to_sheet(rows);
const workbook = utils.book_new();
utils.book_append_sheet(workbook, worksheet, "Dates");

/* fix headers */
utils.sheet_add_aoa(worksheet, [["Name", "Birthday"]], { origin: "A1" });

/* calculate column width */
const max_width = rows.reduce((w, r) => Math.max(w, r.name.length), 10);
worksheet["!cols"] = [ { wch: max_width } ];

/* create an XLSX file and try to save to Presidents.xlsx */
writeFileXLSX(workbook, "Presidents.xlsx");
};
  1. 安装 SheetJS NodeJS 模块:

    ¥Install the SheetJS NodeJS module:

yarn add https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz

开发

¥Development

  1. 运行 ParcelJS 开发服务器:

    ¥Run the ParcelJS development server:

npx -y parcel index.html

该过程将打印一个 URL:

¥The process will print a URL:

Server running at http://localhost:1234
  1. 在 Web 浏览器中访问上一步中的 URL(通常为 http://localhost:1234),然后单击 "点击导出!" 按钮以生成文件。

    ¥Access the URL from the previous step (typically http://localhost:1234) in a web browser and click the "Click to Export!" button to generate a file.

生产

¥Production

  1. 编辑 package.json 并删除以下行:

    ¥Edit package.json and remove the following line:

package.json (search for this line and remove)
   "main": "index.js"
  1. 搭建生产站点:

    ¥Build the production site:

npx -y parcel build index.html

制作站点将存放在 dist 文件夹中

¥The production site will be stored in the dist folder

  1. 启动本地 Web 服务器并提供 dist 文件夹:

    ¥Start a local web server and serve the dist folder:

npx http-server dist

在 Web 浏览器中访问显示的 URL(通常为 http://localhost:8080/)。点击 "点击此处导出" 生成文件。

¥Access the displayed URL (typically http://localhost:8080/) in a web browser. Click on "Click here to export" to generate a file.

[^1]: 见 Parcel 问题跟踪器中的问题 523

¥See Issue 523 in the Parcel issue tracker