问题
前端导出的excel需要进行分页处理便于打印,为了方便显示,打印时需要设置打印标题行(每一页都会打印标题)
js-xlsx文档说明
js-xlsx在文档中列出了一下几个属性,但没有具体说明,经过实验,可以得到其具体的作用
- ws[’!rowBreaks’]: array of row break points, e.g. [16,32] // 行分页,数组的值对应插入分页符的行
- ws[’!colBreaks’]: array of col break points, e.g. [8,16] // 列分页,数组的值对应插入分页符的列
- ws[’!pageSetup’]: `{scale: ‘100’, orientation: ‘portrait’||‘landscape’} // 打印设置:大小,横纵向
- ws[’!printHeader’]: array of first and last row indexes for repeat header on printing, e.g. [1,1] to repeat just first row // 打印标题行,打印时每一页都会出现的行
- ws[’!freeze’]: string cell reference for breakpoint, e.g. the following will freeze the first row and first column: { xSplit: “1”, ySplit: “1”, topLeftCell: “B2”, activePane: “bottomRight”, state: “frozen” } // 固定行列
使用说明
sheet['!rowBreaks'] = rowBreak;
sheet['!printHeader'] = printHeader;
其他说明
- js-xlsx导出excel基本原理:即创建并修改符合excel规范的xml文件即可
- 打印标题行实现的修改,目前引用的js-xlsx版本(0.8.11) 对打印标题行的处理是有问题的,无法正确设置,原因在于将配置好的!printHeader属性写入xml文件时,格式不符合excel定义。
正确的excel的xml格式如下:
- 其中定义了每个sheet需要的打印标题行
- 格式为(sheet名称) !$ (开始行) : (结束行)
<?xml version="1.0" encoding="utf-8"?>
<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:x15="http://schemas.microsoft.com/office/spreadsheetml/2010/11/main" mc:Ignorable="x15">
<fileVersion appName="xl" lastEdited="6" lowestEdited="6" rupBuild="14420"/>
<workbookPr defaultThemeVersion="164011"/>
<mc:AlternateContent>
<mc:Choice Requires="x15">
<x15ac:absPath xmlns:x15ac="http://schemas.microsoft.com/office/spreadsheetml/2010/11/ac" url="C:\Users\xuyh-f\Desktop\"></x15ac:absPath>
</mc:Choice>
</mc:AlternateContent>
<bookViews>
<workbookView xWindow="0" yWindow="0" windowWidth="28800" windowHeight="13530"/>
</bookViews>
<sheets>
<sheet name="Sheet1" sheetId="1" r:id="rId1"/>
</sheets>
<definedNames>
<definedName name="_xlnm.Print_Titles" localSheetId="0">Sheet1!$1:$1</definedName>
</definedNames>
<calcPr calcId="162913"/>
<extLst>
<ext uri="{140A7094-0E35-4892-8432-C4D2E57EDEB5}">
<x15:workbookPr chartTrackingRefBase="1"/>
</ext>
</extLst>
</workbook>
而0.8.11版本的js-xlsx的代码定义的格式是错误的,按excel格式要求修改后即可正常使用,js-xlsx最新版本已经更改为正确的的配置了,感兴趣可以看一下最新的代码,除了修改配置外还加了其他判断
// 0.8.11版本
// 这个地方excel格式配置有问题,代码格式也有问题
var range = "'" + sheetName + "'!" + sheet['!printHeader'];
console.log("!!!!"+range)
o[o.length] = (writextag('definedName', range, {
"name":"_xlnm.Print_Titles",
localSheetId : ''+i
}))
// 修改后
//定义打印标题行 range格式为: SheetName!$1:$1
var range = "'" + sheetName + "'!" + '$' + sheet['!printHeader'][0] + ':' + '$' + sheet['!printHeader'][1];
o[o.length] = (writextag('definedName', range, {
"name":"_xlnm.Print_Titles",
localSheetId : ''+i
}));