Export Table to docx:Vue3 表格輸出成word

Wendy Chang
Wendy Loops
Published in
5 min readNov 24, 2023

公司在進行重構前,表格輸出都使用後端輸出,自從我這個唯一前端出現就這個工作就自然落到我身上嚕。

Export Table to Excel:Vue3 表格輸出成Excel
Export Table to PDF:Vue3 表格輸出成PDF|jsPdf, jsPdf-autotable

輸出word

甲方的合約寫著一定要能輸出word,百思不得其解報表要word幹嘛...但也只能硬著頭皮做了

安裝

npm i docx file-saver

引入

import {
WidthType,
BorderStyle,
Document,
Paragraph,
Packer,
TextRun,
Table,
TableRow,
TableCell,
} from "docx";
import { saveAs } from "file-saver";

表格中第一排要放標題,每一個標題都是一個table cell,注意table cell內的結構:

let headers = ['姓名','性別','電話','職業']

// 輸出成word用的陣列
let wordHeaders = [];

for (let i = 0; i < headers.length; i++) {
wordHeaders.push(
new TableCell({
children: [
new Paragraph({
text: headers[i], // 文字放這裡
bold: true, // 要粗體就加這一行
}),
],
})
);
}

內部資料排列順序需跟headers一致,不然會亂排、對應不到

let data = [
["Frank", "男", "09123456789", "家管"],
["May", "女", "09789456123", "健身教練"],
["Kitty", "女", "02123456996 #5", "大學教授"]
];

let tableRowsArr = [];

for (let row of data) {
let children = [];
for (let cell of row) {
let tableCell = new TableCell({
children: [
new Paragraph({
text: cell
})
]
});
children.push(tableCell);
}
let tableRow = new TableRow({
children
});
tableRowsArr.push(tableRow);
}

將整理好的table丟進word中

let doc = new Document({
sections: [
{
properties: {},
children: [
new Paragraph({
children: [
new TextRun({
text: "標題",
bold: true
})
]
}),
new Table({
rows: [
new TableRow({
children: wordHeaders
}),
...tableRowsArr
]
})
]
}
]
});

存檔

function saveWord(doc, fileName) {
const mimeType =
"application/vnd.openxmlformats officedocument.wordprocessingml.document";
Packer.toBlob(doc).then((blob) => {
const docblob = blob.slice(0, blob.size, mimeType);
saveAs(docblob, fileName);
});
}

將存檔的function丟到上一個function中

const exportWord = ()=>{
// new TableCell...new Paragraph...
// 建立好doc

saveWord(doc, '標題.docx')
}

把exportWord掛載到要執行的button就可以了。

這個套件要注意的是結構:

new Document
--children
----new Table
------rows
--------new TableRow //headers那行
----------children
------------new TableCell
--------------children
----------------new Paragraph
--------new TableRow //資料第一行
----------children
------------new TableCell
--------new TableRow //資料第二行
----------children
------------new TableCell...

可參考codepen:https://codepen.io/wendy725/pen/BaMxXZR?editors=1011
因為不是用vue寫的,所以在使用docx套件時(new TableRow等),要加上docx呼叫:new docx.TableRow

參考資料
https://hvekriya.medium.com/creating-word-document-with-vue-js-1d10eae37ddb
https://www.npmjs.com/package/docx

輸出成其他格式
Export Table to Excel:Vue3 表格輸出成Excel
Export Table to PDF:Vue3 表格輸出成PDF|jsPdf, jsPdf-autotable

--

--

Wendy Chang
Wendy Loops

什麼都寫ㄉ前端工程師 / 影片剪輯師 / 自媒體經營者