问题
一直在使用SheetJS Community Edition,也就是它的社区版本,看到文档里面提到了对每个Cell层面的样式控制(cell-object),尝试了一次都没有输出效果。后面查阅了一些资料,发现SheetJS社区版,不能对导出的excel文件进行样式设置,只要寻求其他途径解决。
过程
发现这一点(不能设置输出文件样式)之后,开始翻看SheetJS的问答区域的关于style的所有问题,在查看的过程中,发现一个demo例子,能够实现基本样式控制:JSFiddle: https://jsfiddle.net/1g24vowu/1/
解决
使用js-xlsx改良过的版本,这个SheetJS分支版本为SheetJS社区版本添加了输出文件颜色设置,真的是要感谢这位xSirrioNx的贡献。
创建样式对象
excelCell
var excelCell = { v: "", t: "s", s: { fill: { patternType: "none", fgColor: {rgb: "FF000000"}, bgColor: {rgb: "FFFFFFFF"} }, font: { name: 'Times New Roman', sz: 16, color: {rgb: "#FF000000"}, bold: false, italic: false, underline: false }, alignment: { vertical: "center", horizontal: "center", indent:0, wrapText: true }, border: { top: {style: "thin", color: {auto: 1}}, right: {style: "thin", color: {auto: 1}}, bottom: {style: "thin", color: {auto: 1}}, left: {style: "thin", color: {auto: 1}} } }};
headerCellStyle
var headerCellStyle = { fill: { patternType: "solid", fgColor: {rgb: "FFdbdbdb"}, bgColor: {rgb: "FFdbdbdb"} }, alignment: { vertical: "center", horizontal: "center", indent:0, wrapText: true }, border: { top: {style: "thin", color: {auto: 1}}, right: {style: "thin", color: {auto: 1}}, bottom: {style: "thin", color: {auto: 1}}, left: {style: "thin", color: {auto: 1}} }};
设置样式对象
这里设置的是第一行的单元格样式。
var headeRange = {s:{c:0, r:0}, e:{c:16, r:0}};for (var R = headeRange.s.r; R <= headeRange.e.r; ++R) { for (var C = headeRange.s.c; C <= headeRange.e.c; ++C) { var cell_address = { c: C, r: R }; /* if an A1-style address is needed, encode the address */ var cell_ref = XLSX.utils.encode_cell(cell_address); var cell = ws[cell_ref]; if(!$.isEmptyObject(cell)){ cell.s = headerCellStyle; } else { ws[cell_ref] = excelCell; } }}
总结
导出Excel库,有点少。还有一个叫:handsontable,据说很好用,不过导出excel功能是需要付费的,以后碰到土豪boss,再考虑考虑。
参考:
xSirrioNx/js-xlsx
SheetJS/js-xlsx
protobi/js-xlsx注:本文内容来自互联网,旨在为开发者提供分享、交流的平台。如有涉及文章版权等事宜,请你联系站长进行处理。