简介
读取,操作并写入电子表格数据和样式到 XLSX 和 JSON 文件。 一个 Excel 电子表格文件逆向工程项目。 注意:excelJS 没有实现 Brower 端操作文件,如果要解析 **.xlsx 文件只能在 node 端
安装或引入
// ExcelJS 在 dist/ 文件夹内发布了两个支持浏览器的包:
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-polyfill/6.26.0/polyfill.js"></script>
<script src="exceljs.js"></script>
// 使用 npm:
npm install exceljs
import * as XLSX from 'xlsx';
json转excel文件
async function jsonToExcel() {
/* 创建一个工作薄 */
const workbook = new window.ExcelJS.Workbook();
/* 创建sheet对象 */
const sheet = workbook.addWorksheet('表一');
/* 添加表头 */
sheet.columns = [
{
header: '工号',
key: 'id',
width: 15,
// style: {
// font: { name: 'Arial', size: 12 },
// border: {
// top: { style: 'thin' },
// left: { style: 'thin' },
// bottom: { style: 'thin' },
// right: { style: 'thin' },
// },
// alignment: {
// vertical: 'middle',
// horizontal: 'center',
// },
// },
},
{ header: '姓名', key: 'name', width: 15 },
];
/* 需要添加的数据 */
const data = [
{
id: 'wb-01',
name: '丁博洋',
},
{
id: 'wb-02',
name: '丁博洋',
},
];
/* 将数据一行一行添加到sheet对象中 */
data.forEach((item) => sheet.addRow(item));
/* 遍历工作表的行row */
sheet.eachRow((row, rowNumber) => {
/* 遍历工作表的列cell */
row.eachCell((cell, colNumber) => {
// 设置第一行样式
if (rowNumber === 1) {
// 设置对齐样式
cell.alignment = { vertical: 'middle', horizontal: 'center', wrapText: true };
// 设置字体样式
cell.font = { bold: true, size: 14, name: 'Arial' };
// 设置背景样式
cell.fill = {
type: 'pattern',
pattern: 'solid',
fgColor: { argb: 'FF5050E6' },
};
}
// 设置边框
cell.border = {
top: { style: 'thin' },
left: { style: 'thin' },
bottom: { style: 'thin' },
right: { style: 'thin' },
};
// 设置列宽
// sheet.getColumn(colNumber).width = 25;
});
// 设置行高
row.height = 25;
});
/* 将工作表转为 buffer 对象 */
const buffer = await workbook.xlsx.writeBuffer();
/* 将 buffer 装化成blob对象 */
var blob = new Blob([buffer], {
type: 'application/octet-stream',
});
/* 下载 blob 文件 */
openDownloadDialog(blob, `模板.xlsx`);
}
// 将blob对象创建bloburl,然后用a标签实现弹出下载框
function openDownloadDialog(blob, fileName) {
const link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = fileName;
link.click();
window.URL.revokeObjectURL(link.href);
}
excel转json
注意:exceljs 在浏览器端是不能操作文件,在nodejs项目中就可以使用它来读取、编辑.xlsx文件