SheetJS 笔记

2024-01-09  本文已影响0人  欢欣的膜笛

用于前端操作Excel以及类似的二维表,js-xlsx是它的社区版本
文档地址:https://docs.sheetjs.com/https://github.com/rockboom/SheetJS-docs-zh-CN
安装
npm install xlsx --save

读取文件

read

readFile

写入文件

write

writeFile

writeFileAsync

writeFileSync

utils Functions

Arrays of Data

aoa_to_sheet
sheet_add_aoa
/* Start from an empty worksheet */
const ws = XLSX.utils.aoa_to_sheet([[]]);
  
/* First row */
XLSX.utils.sheet_add_aoa(ws, [ "SheetJS".split("") ], {origin: "A1"});

/* Write data starting at A2 */
XLSX.utils.sheet_add_aoa(ws, [[1,2], [2,3], [3,4]], {origin: "A2"});

/* Write data starting at E2 */
// r: row; c: column
XLSX.utils.sheet_add_aoa(ws, [[5,6,7], [6,7,8], [7,8,9]], {origin:{r:1, c:4}});

/* Append row */
// 从第一列开始附加到工作表底部
XLSX.utils.sheet_add_aoa(ws, [[4,5,6,7,8,9,0]], {origin: -1});
json_to_sheet
const aoo = [
    { Name: "Bill Clinton", Index: 42 },
    { Name: "GeorgeW Bush", Index: 43 },
    { Name: "Barack Obama", Index: 44 },
    { Name: "Donald Trump", Index: 45 },
    { Name: "Joseph Biden", Index: 46 }
  ]
  const ws = XLSX.utils.json_to_sheet(aoo)
sheet_add_json
sheet_to_json

HTML

sheet_to_html
table_to_book、table_to_sheet
const wb = XLSX.utils.table_to_book(document.getElementById('table'))
const ws = XLSX.utils.table_to_sheet(document.getElementById('table'))
sheet_add_dom

CSV and Text

sheet_to_csv
sheet_to_txt

Array of Formulae

sheet_to_formulae

Workbook Helpers

book_new
book_append_sheet

单元格操作

转换单元格地址

const cell1 = XLSX.utils.encode_cell({c:0, r:0}) // 返回 A1
const cell2 = XLSX.utils.decode_cell('A1') // 返回 {c:0, r:0}

// 获取单元格对象
const cell = worksheet['A1'] // 含 数据类型、值、格式、公式、样式等等

转换行地址

转换列地址
const col1 = XLSX.utils.encode_col(3) // 返回 D
const col2 = XLSX.utils.decode_col('D') // 返回 索引 3

生成文本类型的单元格值

合并单元格

// s = start, r = row, c=col, e= end
worksheet.merge = [{ s: { r: 0, c: 0 }, e: { r: 0, c: c } }]

配置超链接

worksheet['A3'].l = { Target:"http://sheetjs.com", Tooltip:"Find us @ SheetJS.com!" }
worksheet['A2'].l = { Target:"#E2" }; /* link to cell E2 */

单元格注释

if(!worksheet.A1.c) worksheet.A1.c = [];
worksheet.A1.c.push({a:"SheetJS", t:"This comment is visible"});

if(!worksheet.A2.c) worksheet.A2.c = [];
worksheet.A2.c.hidden = true;
worksheet.A2.c.push({a:"SheetJS", t:"This comment will be hidden"});

数据表对象

worksheet['!ref']

worksheet['!margins']

worksheet['!merges']

工作簿对象

workbook.SheetNames

workbook.Sheets[sheetname]

上一篇下一篇

猜你喜欢

热点阅读