nodeJS生成xlsx以及設置樣式

參考:node

https://www.npmjs.com/package/xlsx-stylegit

https://www.jianshu.com/p/877631e7e411npm

https://sheetjs.gitbooks.io/docs/#streaming-read數組

ps:以上第一個連接中的文檔是錯誤的:ui

文字的水平對齊方式應該是:left center right 三個值纔對spa

 

 安裝依賴:npm install xlsx-style node-xlsx xlsx,安裝的依賴版本:code

"dependencies": { "node-xlsx": "^0.15.0", "xlsx": "^0.14.4", "xlsx-style": "^0.8.13" }

 

把以上三個js文件拷貝到自定義目錄,如node-xlsx-cblog

修改代碼node-xlsx-c/index.js: xlsx修改成xlsx-styleci

編寫生成xlsx的代碼:文檔

const fs = require("fs"); /** * 生成xlsx * @param p 生成文件路徑 * @param cols 列名 * @param data 行,二維數組 */
function genXlsx(p, cols, data) { let nodeXlsx = require('./node-xlsx-c'); let d = [{ name: "Sheet1", data: [ cols, ...data ] }]; // !cols 指定列的寬度
 fs.writeFileSync(p, nodeXlsx.build(d, { '!cols': [{wch: 60}, {wch: 20}] }), {'flag': 'w'}); } // 指定單元格內容樣式:四個方向的黑邊框
let contentCellStyle = { border: { top: { style: "medium", color: "#000" }, bottom: { style: "medium", color: "#000" }, left: { style: "medium", color: "#000" }, right: { style: "medium", color: "#000" }, } }; // 指定標題單元格樣式:加粗居中
let headerStyle = { font: { bold: true }, alignment: { horizontal: "center" } } genXlsx("1.xlsx", [{ v: "表頭1", s: headerStyle }, { v: "表頭2", s: headerStyle }], [[{ v: 123, s: contentCellStyle }, { v: 456, s: contentCellStyle }]])

代碼運行,在當前目錄生成1.xlsx:

相關文章
相關標籤/搜索