其他分享
首页 > 其他分享> > sheetjs 使用简介

sheetjs 使用简介

作者:互联网

xlsx js 的使用笔记

最近项目需要前端导出excel,以及解析excel,使用了 xlsx 这个包。简单介绍一下遇到的问题和快速上手使用代码。

import xlsx from 'xlsx';

// write rows:any[][] to some sheet
createSheetFromAoa(aoa: any[][]) {
    let ws = xlsx.utils.aoa_to_sheet(aoa);
    ws['!cols'] = this.fitToColumn(aoa);
    return ws;
  }

// just make the cells auto-fit, make the width to the max width of same column
  fitToColumn(arrayOfArray: any[][]) {
    // get maximum character of each column
    return arrayOfArray[0].map((a, i) => ({
      wch:
        Math.max(
          ...arrayOfArray
            .map((a2) => a2[i]?.toString()?.length)
            .filter((it) => it > 0)
        ) + 3,
    }));
  }

const rows=[
    ['head1','head2','head3'],
    [1,2,3],
    [4,5,6],
    [7,8,9]
]
// create workbook first
const wb: xlsx.WorkBook = xlsx.utils.book_new();
const ws: xlsx.WorkSheet = createSheetFromAoa(rows);
xlsx.utils.book_append_sheet(wb,ws,'TabName');
xlsx.writeFile(wb, 'helloworld.xlsx');
const reader = new FileReader();
reader.onload = (e) => {
    var data = new Uint8Array(e.target.result as any);
    let wb = xlsx.read(data, {
        type: 'array',
    });
    this.parseWorkBook(wb);
};
reader.readAsArrayBuffer(this._uploadedFile as File);

//parse workbook
function parseWorkBook(wb:xlsx.WorkBook){
    const ws = wb.Sheets['TabName'];
    // mark the first row is header
    const rows = xlsx.utils.sheet_to_json(ws,{header:1});
    const header=rows[0];
    const body = rows.slice(1);
}
getDateMapping() {
    return {
      toexcel: (val: string) => {
        try {
          return val?.length ? DateTime.fromISO(val).toJSDate() : null;
        } catch (ex) {
          return null;
        }
      },
      fromexcel: (val: number) => {
        try {
          //https://github.com/SheetJS/sheetjs/issues/1223
          return val > 0
            ? DateTime.fromMillis(Math.round((val - 25569) * 86400 * 1000))
                .setZone('utc')
                .toFormat('yyyy-MM-dd')
            : null;
        } catch (ex) {
          return null;
        }
      },
    };
  }
function write_ws_xml_datavalidation(validations) {
	var o = '<dataValidations>';
	for(var i=0; i < validations.length; i++) {
		var validation = validations[i];
		o += '<dataValidation type="list" allowBlank="1" sqref="' + validation.sqref + '">';
		o += '<formula1>"'+validation.values+'"</formula1>';
		o += '</dataValidation>';
	}
	o += '</dataValidations>';
	return o;
};

然后在write_ws_xml 找到如下片段,做如下修改

    if(ws['!merges'] != null && ws['!merges'].length > 0) o[o.length] = (write_ws_xml_merges(ws['!merges']));
+	if(ws['!dataValidation']!=null && ws['!dataValidation'].length>0) o[o.length] = write_ws_xml_datavalidation(ws['!dataValidation']);

"uglifyjs-xlsx": "uglifyjs xlsx.js -o ./dist/xlsx.min.js --source-map ./dist/xlsx.min.map"

标签:npm,xlsx,const,简介,excel,sheetjs,ws,使用,return
来源: https://www.cnblogs.com/kongshu-612/p/15106858.html