rpt_excel_util.js 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188
  1. 'use strict';
  2. /**
  3. * Created by Tony on 2017/4/1.
  4. */
  5. const JV = require('../rpt_component/jpc_value_define');
  6. const fs = require('fs');
  7. const JSZip = require('jszip');
  8. const strUtil = require('../public/stringUtil');
  9. const jpcCmnHelper = require('../rpt_component/helper/jpc_helper_common');
  10. const DPI = jpcCmnHelper.getScreenDPI()[0];
  11. const fsUtil = require('../public/fsUtil');
  12. const dftHeadXml = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>';
  13. const uuidV1 = require('uuid/v1');
  14. function writeContentTypes(sheets, isSinglePage, hasSignature) {
  15. const rst = [];
  16. rst.push(dftHeadXml + '\r\n');
  17. rst.push('<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">');
  18. rst.push('<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>');
  19. rst.push('<Default Extension="xml" ContentType="application/xml"/>');
  20. if (hasSignature) {
  21. rst.push('<Default Extension="png" ContentType="image/png"/>');
  22. }
  23. rst.push('<Override PartName="/xl/theme/theme1.xml" ContentType="application/vnd.openxmlformats-officedocument.theme+xml"/>');
  24. rst.push('<Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/>');
  25. rst.push('<Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>');
  26. rst.push('<Override PartName="/docProps/app.xml" ContentType="application/vnd.openxmlformats-officedocument.extended-properties+xml"/>');
  27. rst.push('<Override PartName="/xl/sharedStrings.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml"/>');
  28. if (isSinglePage) {
  29. rst.push('<Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>');
  30. if (hasSignature) {
  31. rst.push('<Override PartName="/xl/drawings/drawing1.xml" ContentType="application/vnd.openxmlformats-officedocument.drawing+xml"/>');
  32. }
  33. } else {
  34. for (let i = 0; i < sheets.length; i++) {
  35. rst.push('<Override PartName="/xl/worksheets/sheet' + (i + 1) + '.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>');
  36. if (hasSignature) {
  37. rst.push('<Override PartName="/xl/drawings/drawing' + (i + 1) + '.xml" ContentType="application/vnd.openxmlformats-officedocument.drawing+xml"/>');
  38. }
  39. }
  40. }
  41. rst.push('<Override PartName="/docProps/core.xml" ContentType="application/vnd.openxmlformats-package.core-properties+xml"/>');
  42. rst.push('</Types>');
  43. return rst;
  44. }
  45. function writeRootRels() {
  46. const rst = [];
  47. rst.push(dftHeadXml + '\r\n');
  48. rst.push('<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">');
  49. rst.push('<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/>');
  50. rst.push('<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties" Target="docProps/core.xml"/>');
  51. rst.push('<Relationship Id="rId3" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties" Target="docProps/app.xml"/>');
  52. rst.push('</Relationships>');
  53. return rst;
  54. }
  55. function writeApp(sheets, isSinglePage) {
  56. const rst = [];
  57. rst.push(dftHeadXml + '\r\n');
  58. rst.push('<Properties xmlns="http://schemas.openxmlformats.org/officeDocument/2006/extended-properties" xmlns:vt="http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes">');
  59. rst.push('<Application>Microsoft Excel</Application>');
  60. rst.push('<DocSecurity>0</DocSecurity>');
  61. rst.push('<ScaleCrop>false</ScaleCrop>');
  62. rst.push('<HeadingPairs>');
  63. rst.push('<vt:vector size="2" baseType="variant">');
  64. rst.push('<vt:variant><vt:lpstr>工作表</vt:lpstr></vt:variant>');
  65. if (isSinglePage) rst.push('<vt:variant><vt:i4>1</vt:i4></vt:variant>');
  66. else rst.push('<vt:variant><vt:i4>' + sheets.length + '</vt:i4></vt:variant>');
  67. rst.push('</vt:vector>');
  68. rst.push('</HeadingPairs>');
  69. rst.push('<TitlesOfParts>');
  70. if (isSinglePage) {
  71. rst.push('<vt:vector size="1" baseType="lpstr">');
  72. rst.push('<vt:lpstr>' + sheets[0].sheetName + '</vt:lpstr>');
  73. } else {
  74. rst.push('<vt:vector size="' + sheets.length + '" baseType="lpstr">');
  75. for (let i = 0; i < sheets.length; i++) {
  76. rst.push('<vt:lpstr>' + sheets[i].sheetName + '</vt:lpstr>');
  77. }
  78. }
  79. rst.push('</vt:vector>');
  80. rst.push('</TitlesOfParts>');
  81. rst.push('<Company>SmartCost</Company>');
  82. rst.push('<LinksUpToDate>false</LinksUpToDate>');
  83. rst.push('<SharedDoc>false</SharedDoc>');
  84. rst.push('<HyperlinksChanged>false</HyperlinksChanged>');
  85. rst.push('<AppVersion>12.0000</AppVersion>');
  86. rst.push('</Properties>');
  87. return rst;
  88. }
  89. function writeCore() {
  90. const rst = [];
  91. const p_fillZero = function(val) {
  92. let rst = val;
  93. if (val < 10) {
  94. rst = '0' + val;
  95. }
  96. return rst;
  97. };
  98. rst.push(dftHeadXml + '\r\n');
  99. rst.push('<cp:coreProperties xmlns:cp="http://schemas.openxmlformats.org/package/2006/metadata/core-properties" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:dcmitype="http://purl.org/dc/dcmitype/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">');
  100. rst.push('<dc:creator>SmartCost</dc:creator>');
  101. rst.push('<cp:lastModifiedBy>SmartCost</cp:lastModifiedBy>');
  102. const dt = new Date();
  103. dt.setDate(dt.getDate() - 8 / 24); // it's GMT time, so please add the server offset time ( -8 hours )
  104. const dtStr = dt.getFullYear() + '-' + p_fillZero(dt.getMonth() + 1) + '-' + p_fillZero(dt.getDate()) + 'T' +
  105. p_fillZero(dt.getHours()) + ':' + p_fillZero(dt.getMinutes()) + ':' + p_fillZero(dt.getSeconds()) + 'Z';
  106. rst.push('<dcterms:created xsi:type="dcterms:W3CDTF">' + dtStr + '</dcterms:created>');
  107. rst.push('<dcterms:modified xsi:type="dcterms:W3CDTF">' + dtStr + '</dcterms:modified>');
  108. rst.push('</cp:coreProperties>');
  109. return rst;
  110. }
  111. function writeXlWorkBook(sheets, isSinglePage) {
  112. const rst = [];
  113. rst.push(dftHeadXml + '\r\n');
  114. rst.push('<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">');
  115. rst.push('<fileVersion appName="xl" lastEdited="4" lowestEdited="4" rupBuild="4505"/>');
  116. rst.push('<workbookPr defaultThemeVersion="124226"/>');
  117. rst.push('<bookViews><workbookView xWindow="360" yWindow="345" windowWidth="14655" windowHeight="4305"/></bookViews>');
  118. rst.push('<sheets>');
  119. if (isSinglePage) {
  120. rst.push('<sheet name="' + sheets[0].sheetName + '" sheetId="1" r:id="rId1"/>');
  121. } else {
  122. for (let i = 0; i < sheets.length; i++) {
  123. rst.push('<sheet name="' + sheets[i].sheetName + '" sheetId="' + (i + 1) + '" r:id="rId' + (i + 1) + '"/>');
  124. }
  125. }
  126. rst.push('</sheets>');
  127. rst.push('<calcPr calcId="124519"/>');
  128. rst.push('</workbook>');
  129. return rst;
  130. }
  131. function writeXlRels(sheets, isSinglePage) {
  132. const rst = [];
  133. let idx = 1;
  134. rst.push(dftHeadXml + '\r\n');
  135. rst.push('<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">');
  136. if (isSinglePage) {
  137. rst.push('<Relationship Id="rId' + idx + '" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/>');
  138. idx++;
  139. } else {
  140. for (let i = 0; i < sheets.length; i++) {
  141. rst.push('<Relationship Id="rId' + idx + '" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet' + (i + 1) + '.xml"/>');
  142. idx++;
  143. }
  144. }
  145. rst.push('<Relationship Id="rId' + idx + '" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme" Target="theme/theme1.xml"/>');
  146. idx++;
  147. rst.push('<Relationship Id="rId' + idx + '" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>');
  148. idx++;
  149. rst.push('<Relationship Id="rId' + idx + '" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings" Target="sharedStrings.xml"/>');
  150. rst.push('</Relationships>');
  151. return rst;
  152. }
  153. function writeTheme() {
  154. const rst = fs.readFileSync(__dirname + '/excel_base_files/theme1.xml', 'utf8', 'r');
  155. return rst;
  156. }
  157. function writeStyles(stylesObj, hasSignature) {
  158. const rst = [];
  159. rst.push(dftHeadXml + '\r\n');
  160. rst.push('<styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">');
  161. // 1. push fonts
  162. rst.push('<fonts count="' + stylesObj.fonts.length + '">');
  163. for (let i = 0; i < stylesObj.fonts.length; i++) {
  164. const font = stylesObj.fonts[i];
  165. rst.push('<font>');
  166. if (strUtil.convertStrToBoolean(font[JV.FONT_PROPS[JV.FONT_PROP_IDX_BOLD]])) {
  167. rst.push('<b/>');
  168. }
  169. if (strUtil.convertStrToBoolean(font[JV.FONT_PROPS[JV.FONT_PROP_IDX_ITALIC]])) {
  170. rst.push('<i/>');
  171. }
  172. if (strUtil.convertStrToBoolean(font[JV.FONT_PROPS[JV.FONT_PROP_IDX_UNDERLINE]])) {
  173. rst.push('<u/>');
  174. }
  175. rst.push('<sz val="' + font.size + '"/>');
  176. rst.push('<color indexed="' + font.colorIdx + '"/>');
  177. rst.push('<name val="' + font[JV.FONT_PROPS[JV.FONT_PROP_IDX_NAME]] + '"/>');
  178. rst.push('<charset val="' + font.charset + '"/>');
  179. rst.push('</font>');
  180. }
  181. rst.push('</fonts>');
  182. // 2. push default fills
  183. rst.push('<fills count="2"><fill><patternFill patternType="none" /></fill><fill><patternFill patternType="gray125" /></fill></fills>');
  184. // 3. push borders
  185. rst.push('<borders count="' + stylesObj.borders.length + '">');
  186. const private_setBorder = function(border, borderDirection) {
  187. if (parseInt(border[borderDirection][JV.PROP_LINE_WEIGHT]) === 0) {
  188. rst.push('<' + borderDirection.toLowerCase() + '/>');
  189. } else {
  190. let bW = 'thin';
  191. if (parseInt(border[borderDirection][JV.PROP_LINE_WEIGHT]) === 2) bW = 'medium';
  192. if (parseInt(border[borderDirection][JV.PROP_LINE_WEIGHT]) > 2) bW = 'thick';
  193. rst.push('<' + borderDirection.toLowerCase() + ' style="' + bW + '"><color indexed="64"/></' + borderDirection.toLowerCase() + '>');
  194. }
  195. };
  196. for (let i = 0; i < stylesObj.borders.length; i++) {
  197. const border = stylesObj.borders[i];
  198. rst.push('<border>');
  199. private_setBorder(border, JV.PROP_LEFT);
  200. private_setBorder(border, JV.PROP_RIGHT);
  201. private_setBorder(border, JV.PROP_TOP);
  202. private_setBorder(border, JV.PROP_BOTTOM);
  203. rst.push('<diagonal />');
  204. rst.push('</border>');
  205. }
  206. rst.push('</borders>');
  207. // 4. push cellStyleXfs
  208. rst.push('<cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"><alignment vertical="center"/></xf></cellStyleXfs>');
  209. // 5. push cellXfs
  210. rst.push('<cellXfs count="' + stylesObj.cellXfs.length + '">');
  211. for (let i = 0; i < stylesObj.cellXfs.length; i++) {
  212. const excelStyle = stylesObj.cellXfs[i];
  213. rst.push('<xf numFmtId="0" fontId="' + excelStyle.fontId + '" fillId="0" borderId="' + excelStyle.borderId + '" xfId="0">');
  214. // pageData[JV.NODE_FONT_COLLECTION] excelStyle.fontId
  215. let alignStr = '<alignment';
  216. let textRotation = 0;
  217. let newHorizontal = excelStyle[JV.CONTROL_PROPS[2]];
  218. let newVertical = excelStyle[JV.CONTROL_PROPS[3]];
  219. if (excelStyle[JV.CONTROL_PROPS[5]] && !strUtil.convertStrToBoolean(excelStyle[JV.CONTROL_PROPS[JV.CONTROL_PROP_IDX_CLOSE_OUTPUT]])) {
  220. newVertical = excelStyle[JV.CONTROL_PROPS[5]];
  221. }
  222. if (parseInt(excelStyle.fontAngle) !== 0) {
  223. let tmpH = newHorizontal;
  224. let tmpV = newVertical;
  225. if (excelStyle.fontAngle > 0) {
  226. textRotation = 180;
  227. if (newHorizontal === 'left') {
  228. tmpV = 'top';
  229. } else if (newHorizontal === 'right') {
  230. tmpV = 'bottom';
  231. } else {
  232. tmpV = 'center';
  233. }
  234. if (newVertical === 'top') {
  235. tmpH = 'right';
  236. } else if (newVertical === 'bottom') {
  237. tmpH = 'left';
  238. } else if (newVertical === 'justify') {
  239. tmpH = 'justify';
  240. } else {
  241. tmpH = 'center';
  242. }
  243. } else {
  244. textRotation = 90;
  245. if (newHorizontal === 'left') {
  246. tmpV = 'bottom';
  247. } else if (newHorizontal === 'right') {
  248. tmpV = 'top';
  249. } else {
  250. tmpV = 'center';
  251. }
  252. if (newVertical === 'top') {
  253. tmpH = 'left';
  254. } else if (newVertical === 'bottom') {
  255. tmpH = 'right';
  256. } else {
  257. tmpH = 'center';
  258. }
  259. }
  260. newHorizontal = tmpH;
  261. newVertical = tmpV;
  262. }
  263. alignStr += ' horizontal="' + newHorizontal + '" vertical="' + newVertical + '"';
  264. if (strUtil.convertStrToBoolean(excelStyle[JV.CONTROL_PROPS[0]])) {
  265. alignStr += ' shrinkToFit="1"';
  266. }
  267. if (strUtil.convertStrToBoolean(excelStyle[JV.CONTROL_PROPS[4]]) && !strUtil.convertStrToBoolean(excelStyle[JV.CONTROL_PROPS[6]])) {
  268. alignStr += ' wrapText="1"';
  269. }
  270. if (textRotation !== 0) {
  271. alignStr += ' textRotation="' + textRotation + '"';
  272. }
  273. alignStr += '/>';
  274. rst.push(alignStr);
  275. rst.push('</xf>');
  276. }
  277. rst.push('</cellXfs>');
  278. // 6. others (xfl style / dxfs / tableStyles)
  279. rst.push('<cellStyles count="1"><cellStyle name="常规" xfId="0" builtinId="0"/></cellStyles>');
  280. rst.push('<dxfs count="0"/>');
  281. rst.push('<tableStyles count="0" defaultTableStyle="TableStyleMedium9" defaultPivotStyle="PivotStyleLight16"/>');
  282. if (hasSignature) {
  283. rst.push('<extLst>');
  284. rst.push('<ext uri="{EB79DEF2-80B8-43e5-95BD-54CBDDF9020C}" xmlns:x14="http://schemas.microsoft.com/office/spreadsheetml/2009/9/main">');
  285. rst.push('<x14:slicerStyles defaultSlicerStyle="SlicerStyleLight1"/>');
  286. rst.push('</ext>');
  287. rst.push('<ext uri="{9260A510-F301-46a8-8635-F512D64BE5F5}" xmlns:x15="http://schemas.microsoft.com/office/spreadsheetml/2010/11/main">');
  288. rst.push('<x15:timelineStyles defaultTimelineStyle="TimeSlicerStyleLight1"/>');
  289. rst.push('</ext>');
  290. rst.push('</extLst>');
  291. }
  292. rst.push('</styleSheet>');
  293. return rst;
  294. }
  295. function writeSharedString(sharedStrList) {
  296. const rst = [];
  297. const pri_func_write = function(cellVal) {
  298. if (cellVal !== null) {
  299. if ((typeof cellVal === 'string') && cellVal.indexOf(' ') === 0) {
  300. rst.push('<si><t xml:space="preserve">' + cellVal + '</t></si>');
  301. } else {
  302. rst.push('<si><t>' + cellVal + '</t></si>');
  303. }
  304. }
  305. };
  306. if (sharedStrList && sharedStrList.length > 0) {
  307. rst.push(dftHeadXml + '\r\n');
  308. rst.push('<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" count="' + sharedStrList.length + '" uniqueCount="' + sharedStrList.length + '">');
  309. const regExp = new RegExp('<', 'gm');
  310. for (let i = 0; i < sharedStrList.length; i++) {
  311. if (typeof sharedStrList[i] === 'string') {
  312. // 转换特殊字符,如 < , 则需要转义一下
  313. sharedStrList[i] = sharedStrList[i].replace(regExp, '&lt;');
  314. if (sharedStrList[i].indexOf('|') >= 0) {
  315. // rst.push('<si><t>' + sharedStrList[i].split('|').join('\r\n') + '</t></si>');
  316. // rst.push('<si><t>' + sharedStrList[i].split('|').join('\n') + '</t></si>');
  317. pri_func_write(sharedStrList[i].split('|').join('\n'));
  318. } else {
  319. // rst.push('<si><t>' + sharedStrList[i] + '</t></si>');
  320. pri_func_write(sharedStrList[i]);
  321. }
  322. // rst.push('<si><t>' + sharedStrList[i].replace('|','\r\n') + '</t></si>');
  323. } else {
  324. // rst.push('<si><t>' + sharedStrList[i] + '</t></si>');
  325. pri_func_write(sharedStrList[i]);
  326. }
  327. }
  328. rst.push('</sst>');
  329. }
  330. return rst;
  331. }
  332. function writeSheets(pageData, paperSize, sharedStrList, stylesObj, isSinglePage, custSheetMergeBands, hasSignature) {
  333. const rst = [];
  334. const private_pushDftFont = function() {
  335. const font = {};
  336. if (!(stylesObj.fonts)) {
  337. stylesObj.fonts = [];
  338. }
  339. font[JV.FONT_PROPS[JV.FONT_PROP_IDX_NAME]] = '宋体'; // font name
  340. font.size = 12;
  341. font.charset = 134;
  342. font.colorIdx = '8';
  343. stylesObj.fonts.push(font);
  344. };
  345. const private_buildFirstDftStyle = function() {
  346. stylesObj.cellXfs = [];
  347. stylesObj.borders = [];
  348. const fontId = 0;
  349. const borderId = 0;
  350. const border = {};
  351. border[JV.PROP_LEFT] = {};
  352. border[JV.PROP_LEFT][JV.PROP_LINE_WEIGHT] = 0;
  353. border[JV.PROP_RIGHT] = {};
  354. border[JV.PROP_RIGHT][JV.PROP_LINE_WEIGHT] = 0;
  355. border[JV.PROP_TOP] = {};
  356. border[JV.PROP_TOP][JV.PROP_LINE_WEIGHT] = 0;
  357. border[JV.PROP_BOTTOM] = {};
  358. border[JV.PROP_BOTTOM][JV.PROP_LINE_WEIGHT] = 0;
  359. stylesObj.borders.push(border);
  360. const cellControl = pageData[JV.NODE_CONTROL_COLLECTION].Default;
  361. const sheetControl = {};
  362. sheetControl.fontId = fontId;
  363. sheetControl.borderId = borderId;
  364. sheetControl.fontAngle = 0;
  365. for (let i = 0; i < JV.CONTROL_PROPS.length; i++) {
  366. sheetControl[JV.CONTROL_PROPS[i]] = cellControl[JV.CONTROL_PROPS[i]];
  367. }
  368. stylesObj.cellXfs.push(sheetControl);
  369. };
  370. private_pushDftFont();
  371. private_buildFirstDftStyle();
  372. let sheetIdx = 0;
  373. if (isSinglePage) {
  374. rst.push(writeSheet(pageData, null, paperSize, sharedStrList, stylesObj, null, hasSignature, sheetIdx));
  375. } else {
  376. for (let i = 0; i < pageData.items.length; i++) {
  377. let appointedMergeBand = null;
  378. if (custSheetMergeBands && custSheetMergeBands.length > i) {
  379. appointedMergeBand = custSheetMergeBands[i];
  380. }
  381. rst.push(writeSheet(pageData, pageData.items[i], paperSize, sharedStrList, stylesObj, appointedMergeBand, hasSignature, sheetIdx));
  382. sheetIdx++;
  383. }
  384. }
  385. return rst;
  386. }
  387. function writeSheet(pageData, sheetData, paperSize, sharedStrList, stylesObj, appointedMergeBand, hasSignature, sheetIdx) {
  388. const rst = [];
  389. const xPos = [];
  390. let yPos = [];
  391. const yMultiPos = [];
  392. let currentMergeBorder = null;
  393. const headerStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  394. let currentPageMergePos = null; // 在 JV.PAGING_OPTION_INFINITY 场合应用
  395. const private_pre_analyze_pos = function() {
  396. let cell;
  397. let pos;
  398. const private_array_sort = function(i1, i2) {
  399. let rst = 0;
  400. if (i1 > i2) { rst = 1; } else
  401. if (i1 < i2) rst = -1;
  402. return rst;
  403. };
  404. const self_analyze_sheet_pos = function(theShtData, theXPos, theYPos) {
  405. for (let i = 0; i < theShtData.cells.length; i++) {
  406. cell = theShtData.cells[i];
  407. pos = cell[JV.PROP_AREA][JV.PROP_LEFT];
  408. if (theXPos.indexOf(pos) < 0) theXPos.push(pos);
  409. pos = cell[JV.PROP_AREA][JV.PROP_RIGHT];
  410. if (theXPos.indexOf(pos) < 0) theXPos.push(pos);
  411. pos = cell[JV.PROP_AREA][JV.PROP_TOP];
  412. if (theYPos.indexOf(pos) < 0) theYPos.push(pos);
  413. pos = cell[JV.PROP_AREA][JV.PROP_BOTTOM];
  414. if (theYPos.indexOf(pos) < 0) theYPos.push(pos);
  415. }
  416. };
  417. xPos.push(0);
  418. if (sheetData) {
  419. // current sheet data
  420. yPos.push(0);
  421. self_analyze_sheet_pos(sheetData, xPos, yPos);
  422. xPos.sort(private_array_sort);
  423. yPos.sort(private_array_sort);
  424. } else {
  425. // total data in one sheet
  426. const marginBottomPos = Math.round((pageData[JV.NODE_PAGE_INFO][JV.NODE_PAGE_SIZE][1] - parseFloat(pageData[JV.NODE_PAGE_INFO][JV.NODE_MARGINS][JV.PROP_BOTTOM]) / 2.54) * DPI);
  427. for (const shtItemData of pageData.items) {
  428. const tmpPos = [];
  429. tmpPos.push(0);
  430. self_analyze_sheet_pos(shtItemData, xPos, tmpPos);
  431. tmpPos.sort(private_array_sort);
  432. if (marginBottomPos - tmpPos[tmpPos.length - 1] > 10) {
  433. // 此逻辑是为了防止打印跨页(假设有些报表模板高度设置离底部margin还好远,导出excel后预览时会发现跨页现象(即下一页的某几行数据会挪到前一页来预览))
  434. tmpPos.push(marginBottomPos - 10);
  435. }
  436. yMultiPos.push(tmpPos);
  437. }
  438. xPos.sort(private_array_sort);
  439. yPos = yMultiPos[0];
  440. }
  441. };
  442. const private_getCellIdxStr = function(idx) {
  443. let rst = 'A';
  444. if (idx < 26) {
  445. rst = headerStr[idx];
  446. } else if (idx < 26 * 26 + 26) {
  447. const ti = Math.floor(idx / 26);
  448. const tj = idx % 26;
  449. rst = headerStr[ti - 1] + headerStr[tj];
  450. } else if (idx < 26 * 26 * 26 + 26) {
  451. const ti = Math.floor(idx / (26 * 26));
  452. const tj = Math.floor((idx - ti * 26 * 26) / 26);
  453. const tk = idx % 26;
  454. rst = headerStr[ti - 1] + headerStr[tj - 1] + headerStr[tk];
  455. }
  456. return rst;
  457. };
  458. const private_getSharedStrIdx = function(val) {
  459. let strVal = val;
  460. if (val === null || val === undefined || (typeof val === 'number' && isNaN(val))) {
  461. strVal = '';
  462. }
  463. let rst = sharedStrList.indexOf(strVal);
  464. if (rst < 0) {
  465. sharedStrList.push(strVal);
  466. rst = sharedStrList.length - 1;
  467. }
  468. return rst;
  469. };
  470. const private_getFontId = function(cell) {
  471. let rst = 0;
  472. let hasFont = false;
  473. if (!(stylesObj.fonts)) {
  474. stylesObj.fonts = [];
  475. // for (let i = 0; i < sheetData.font_collection)
  476. }
  477. let sheetFont = null;
  478. if (typeof cell[JV.PROP_FONT] === 'string') {
  479. sheetFont = pageData[JV.NODE_FONT_COLLECTION][cell[JV.PROP_FONT]];
  480. } else {
  481. sheetFont = cell[JV.PROP_FONT];
  482. }
  483. for (let i = 0; i < stylesObj.fonts.length; i++) {
  484. const font = stylesObj.fonts[i];
  485. if (sheetFont) {
  486. if (font[JV.FONT_PROPS[JV.FONT_PROP_IDX_NAME]] === sheetFont[JV.FONT_PROPS[JV.FONT_PROP_IDX_NAME]] && font.size === Math.floor(sheetFont[JV.FONT_PROPS[1]] * 3 / 4)
  487. && font[JV.FONT_PROPS[JV.FONT_PROP_IDX_BOLD]] === sheetFont[JV.FONT_PROPS[JV.FONT_PROP_IDX_BOLD]] && font[JV.FONT_PROPS[JV.FONT_PROP_IDX_ITALIC]] === sheetFont[JV.FONT_PROPS[JV.FONT_PROP_IDX_ITALIC]]
  488. && font[JV.FONT_PROPS[JV.FONT_PROP_IDX_UNDERLINE]] === sheetFont[JV.FONT_PROPS[JV.FONT_PROP_IDX_UNDERLINE]]) {
  489. hasFont = true;
  490. rst = i;
  491. break;
  492. }
  493. } else {
  494. break;
  495. }
  496. }
  497. if (!hasFont) {
  498. const font = {};
  499. font[JV.FONT_PROPS[JV.FONT_PROP_IDX_NAME]] = sheetFont[JV.FONT_PROPS[JV.FONT_PROP_IDX_NAME]]; // font name
  500. // font.size = Math.round(sheetFont[JV.FONT_PROPS[1]] * 3 / 4);
  501. font.size = Math.floor(sheetFont[JV.FONT_PROPS[1]] * 3 / 4);
  502. font.charset = 134;
  503. font.colorIdx = '8';
  504. font[JV.FONT_PROPS[JV.FONT_PROP_IDX_BOLD]] = sheetFont[JV.FONT_PROPS[JV.FONT_PROP_IDX_BOLD]]; // font bold
  505. font[JV.FONT_PROPS[JV.FONT_PROP_IDX_ITALIC]] = sheetFont[JV.FONT_PROPS[JV.FONT_PROP_IDX_ITALIC]]; // font italic
  506. font[JV.FONT_PROPS[JV.FONT_PROP_IDX_UNDERLINE]] = sheetFont[JV.FONT_PROPS[JV.FONT_PROP_IDX_UNDERLINE]]; // font underline
  507. stylesObj.fonts.push(font);
  508. rst = stylesObj.fonts.length - 1;
  509. }
  510. return rst;
  511. };
  512. const private_chkAndGetMergeLine = function(cell, sheetBorder, borderStr, needFurtherChk) {
  513. let rst = 0;
  514. const mergeBorder = currentMergeBorder;
  515. let mergeBand = pageData[JV.BAND_PROP_MERGE_BAND];
  516. if (appointedMergeBand !== null) {
  517. mergeBand = appointedMergeBand;
  518. }
  519. if (sheetBorder[borderStr] && sheetBorder[borderStr][JV.PROP_LINE_WEIGHT] !== undefined) {
  520. rst = sheetBorder[borderStr][JV.PROP_LINE_WEIGHT];
  521. }
  522. if (currentPageMergePos) {
  523. const side = currentPageMergePos[borderStr];
  524. if (side.indexOf(cell[JV.PROP_AREA][borderStr]) >= 0) {
  525. if (needFurtherChk) {
  526. const topSide = currentPageMergePos[JV.PROP_TOP];
  527. const bottomSide = currentPageMergePos[JV.PROP_BOTTOM];
  528. for (let i = 0; i < topSide.length; i++) {
  529. if (cell[JV.PROP_AREA][JV.PROP_TOP] >= topSide[i]) {
  530. if (cell[JV.PROP_AREA][JV.PROP_BOTTOM] <= bottomSide[i]) {
  531. const destStyle = pageData[JV.NODE_STYLE_COLLECTION][mergeBand[JV.PROP_STYLE][JV.PROP_ID]];
  532. rst = destStyle[borderStr][JV.PROP_LINE_WEIGHT];
  533. break;
  534. }
  535. } else {
  536. break;
  537. }
  538. }
  539. } else {
  540. const destStyle = pageData[JV.NODE_STYLE_COLLECTION][mergeBand[JV.PROP_STYLE][JV.PROP_ID]];
  541. rst = destStyle[borderStr][JV.PROP_LINE_WEIGHT];
  542. }
  543. }
  544. } else {
  545. if (cell[JV.PROP_AREA][borderStr] === mergeBorder[borderStr]) {
  546. const destStyle = pageData[JV.NODE_STYLE_COLLECTION][mergeBand[JV.PROP_STYLE][JV.PROP_ID]];
  547. if (needFurtherChk) {
  548. if (cell[JV.PROP_AREA][JV.PROP_TOP] >= mergeBorder[JV.PROP_TOP] &&
  549. cell[JV.PROP_AREA][JV.PROP_BOTTOM] <= mergeBorder[JV.PROP_BOTTOM]) {
  550. rst = destStyle[borderStr][JV.PROP_LINE_WEIGHT];
  551. }
  552. } else {
  553. rst = destStyle[borderStr][JV.PROP_LINE_WEIGHT];
  554. }
  555. }
  556. }
  557. return parseInt(rst);
  558. };
  559. const private_checkBorder = function(cell, border, sheetBorder) {
  560. let rst = true;
  561. const borderLineWidths = [];
  562. const sheetBorderLineWidths = [];
  563. borderLineWidths.push(border[JV.PROP_LEFT][JV.PROP_LINE_WEIGHT]);
  564. borderLineWidths.push(border[JV.PROP_RIGHT][JV.PROP_LINE_WEIGHT]);
  565. borderLineWidths.push(border[JV.PROP_TOP][JV.PROP_LINE_WEIGHT]);
  566. borderLineWidths.push(border[JV.PROP_BOTTOM][JV.PROP_LINE_WEIGHT]);
  567. if (sheetBorder[JV.PROP_LEFT] && sheetBorder[JV.PROP_LEFT][JV.PROP_LINE_WEIGHT]) {
  568. sheetBorderLineWidths.push(private_chkAndGetMergeLine(cell, sheetBorder, JV.PROP_LEFT, true));
  569. } else {
  570. sheetBorderLineWidths.push(0);
  571. }
  572. if (sheetBorder[JV.PROP_RIGHT] && sheetBorder[JV.PROP_RIGHT][JV.PROP_LINE_WEIGHT]) {
  573. sheetBorderLineWidths.push(private_chkAndGetMergeLine(cell, sheetBorder, JV.PROP_RIGHT, true));
  574. } else {
  575. sheetBorderLineWidths.push(0);
  576. }
  577. if (sheetBorder[JV.PROP_TOP] && sheetBorder[JV.PROP_TOP][JV.PROP_LINE_WEIGHT]) {
  578. sheetBorderLineWidths.push(private_chkAndGetMergeLine(cell, sheetBorder, JV.PROP_TOP, false));
  579. } else {
  580. sheetBorderLineWidths.push(0);
  581. }
  582. if (sheetBorder[JV.PROP_BOTTOM] && sheetBorder[JV.PROP_BOTTOM][JV.PROP_LINE_WEIGHT]) {
  583. sheetBorderLineWidths.push(private_chkAndGetMergeLine(cell, sheetBorder, JV.PROP_BOTTOM, false));
  584. } else {
  585. sheetBorderLineWidths.push(0);
  586. }
  587. for (let i = 0; i < 4; i++) {
  588. if (borderLineWidths[i] != sheetBorderLineWidths[i]) {
  589. rst = false;
  590. break;
  591. }
  592. }
  593. return rst;
  594. };
  595. const private_getIniBorder = function() {
  596. const rst = {};
  597. rst[JV.PROP_LEFT] = {};
  598. rst[JV.PROP_LEFT][JV.PROP_LINE_WEIGHT] = 0;
  599. rst[JV.PROP_RIGHT] = {};
  600. rst[JV.PROP_RIGHT][JV.PROP_LINE_WEIGHT] = 0;
  601. rst[JV.PROP_TOP] = {};
  602. rst[JV.PROP_TOP][JV.PROP_LINE_WEIGHT] = 0;
  603. rst[JV.PROP_BOTTOM] = {};
  604. rst[JV.PROP_BOTTOM][JV.PROP_LINE_WEIGHT] = 0;
  605. return rst;
  606. };
  607. const private_getBorderId = function(cell) {
  608. let rst = 0;
  609. let hasBorder = false;
  610. if (!(stylesObj.borders)) {
  611. stylesObj.borders = [];
  612. }
  613. const sheetBorder = pageData[JV.NODE_STYLE_COLLECTION][cell.style];
  614. const mergedBorder = private_getIniBorder();
  615. mergedBorder[JV.PROP_LEFT][JV.PROP_LINE_WEIGHT] = private_chkAndGetMergeLine(cell, sheetBorder, JV.PROP_LEFT, true);
  616. mergedBorder[JV.PROP_RIGHT][JV.PROP_LINE_WEIGHT] = private_chkAndGetMergeLine(cell, sheetBorder, JV.PROP_RIGHT, true);
  617. mergedBorder[JV.PROP_TOP][JV.PROP_LINE_WEIGHT] = private_chkAndGetMergeLine(cell, sheetBorder, JV.PROP_TOP, false);
  618. mergedBorder[JV.PROP_BOTTOM][JV.PROP_LINE_WEIGHT] = private_chkAndGetMergeLine(cell, sheetBorder, JV.PROP_BOTTOM, false);
  619. for (let i = 0; i < stylesObj.borders.length; i++) {
  620. const border = stylesObj.borders[i];
  621. if (private_checkBorder(cell, border, mergedBorder)) {
  622. hasBorder = true;
  623. rst = i;
  624. break;
  625. }
  626. }
  627. if (!hasBorder) {
  628. stylesObj.borders.push(mergedBorder);
  629. rst = stylesObj.borders.length - 1;
  630. }
  631. return rst;
  632. };
  633. const private_checkControl = function(cellControl, sheetControl) {
  634. let rst = true;
  635. for (let i = 0; i < JV.CONTROL_PROPS.length; i++) {
  636. if (cellControl[JV.CONTROL_PROPS[i]] != sheetControl[JV.CONTROL_PROPS[i]]) {
  637. rst = false;
  638. break;
  639. }
  640. }
  641. return rst;
  642. };
  643. const private_getStyleId = function(cell) {
  644. let rst = 1;
  645. let hasStyle = false;
  646. if (!(stylesObj.cellXfs)) stylesObj.cellXfs = [];
  647. const fontId = private_getFontId(cell);
  648. let fontAngle = 0;
  649. if (typeof cell[JV.PROP_FONT] === 'string') {
  650. fontAngle = parseInt(pageData[JV.NODE_FONT_COLLECTION][cell[JV.PROP_FONT]].FontAngle);
  651. } else {
  652. fontAngle = parseInt(cell[JV.PROP_FONT].FontAngle);
  653. }
  654. const borderId = private_getBorderId(cell);
  655. let cellControl = null;
  656. if (typeof cell[JV.PROP_CONTROL] === 'string') {
  657. cellControl = pageData[JV.NODE_CONTROL_COLLECTION][cell[JV.PROP_CONTROL]];
  658. } else {
  659. cellControl = cell[JV.PROP_CONTROL];
  660. }
  661. for (let i = 0; i < stylesObj.cellXfs.length; i++) {
  662. const sheetControl = stylesObj.cellXfs[i];
  663. if (sheetControl.fontId === fontId && sheetControl.borderId === borderId) {
  664. if (private_checkControl(cellControl, sheetControl)) {
  665. rst = i;
  666. hasStyle = true;
  667. break;
  668. }
  669. }
  670. }
  671. if (!hasStyle) {
  672. const sheetControl = {};
  673. sheetControl.fontId = fontId;
  674. sheetControl.borderId = borderId;
  675. sheetControl.fontAngle = fontAngle;
  676. for (let i = 0; i < JV.CONTROL_PROPS.length; i++) {
  677. sheetControl[JV.CONTROL_PROPS[i]] = cellControl[JV.CONTROL_PROPS[i]];
  678. }
  679. stylesObj.cellXfs.push(sheetControl);
  680. rst = stylesObj.cellXfs.length - 1;
  681. }
  682. return rst;
  683. };
  684. const private_setCols = function() {
  685. // remark: 1 excel unit width = 2.117 mm
  686. rst.push('<cols>');
  687. let w = 0;
  688. for (let i = 1; i < xPos.length - 1; i++) {
  689. w = (xPos[i + 1] - xPos[i]) / DPI * 25.4 / 2.117;
  690. w = Math.round(w * 1000) / 1000;
  691. rst.push('<col min="' + i + '" max="' + i + '" width="' + w + '" customWidth="1"/>');
  692. }
  693. rst.push('<col min="' + (xPos.length - 1) + '" max="' + (xPos.length - 1) + '" width="' + 10 + '" customWidth="1"/>');
  694. rst.push('</cols>');
  695. };
  696. const private_setMergedCells = function() {
  697. let cnt = 0;
  698. rst.push('<mergeCells count="?">');
  699. const startIdx = rst.length - 1;
  700. const self_setMergedCells = function(theData, theYPos, offsetY) {
  701. for (let i = 0; i < theData.cells.length; i++) {
  702. const cell = theData.cells[i];
  703. const idxR = xPos.indexOf(cell[JV.PROP_AREA][JV.PROP_RIGHT]);
  704. const idxL = xPos.indexOf(cell[JV.PROP_AREA][JV.PROP_LEFT]);
  705. const idxB = theYPos.indexOf(cell[JV.PROP_AREA][JV.PROP_BOTTOM]);
  706. const idxT = theYPos.indexOf(cell[JV.PROP_AREA][JV.PROP_TOP]);
  707. if (idxR - idxL > 1 || idxB - idxT > 1) {
  708. rst.push('<mergeCell ref="' + private_getCellIdxStr(idxL - 1) + (idxT + offsetY) + ':' + private_getCellIdxStr(idxR - 2) + (idxB - 1 + offsetY) + '"/>');
  709. cnt++;
  710. }
  711. }
  712. }
  713. if (sheetData) {
  714. self_setMergedCells(sheetData, yPos, 0);
  715. } else {
  716. let osY = 0;
  717. for (let i = 0; i < pageData.items.length; i++) {
  718. const shtItemData = pageData.items[i];
  719. const tmpPos = yMultiPos[i];
  720. self_setMergedCells(shtItemData, tmpPos, osY);
  721. osY += tmpPos.length - 2;
  722. }
  723. }
  724. rst[startIdx] = '<mergeCells count="' + cnt + '">';
  725. rst.push('</mergeCells>');
  726. };
  727. const private_setSheetData = function() {
  728. // remark: 1 excel unit height = 0.3612 mm
  729. rst.push('<sheetData>');
  730. const spanX = xPos.length - 2;
  731. let cellIdx = 0;
  732. let h = 0;
  733. const self_setDataEx = function(theShtData, theYPos, offsetY) {
  734. const rows = [];
  735. // 1. build full set of blank rows/cells
  736. for (let i = 1; i < theYPos.length - 1; i++) {
  737. const rowObj = {};
  738. h = (theYPos[i + 1] - theYPos[i]) / DPI * 25.4 / 0.3612;
  739. h = Math.round(h * 1000) / 1000;
  740. rowObj.height = h;
  741. rowObj.r = i + offsetY;
  742. rowObj.items = [];
  743. rows.push(rowObj);
  744. for (let j = 1; j < xPos.length - 1; j++) {
  745. const colIdxStr = private_getCellIdxStr(j - 1);
  746. const cellObj = {};
  747. cellObj.r = colIdxStr + (i + offsetY);
  748. cellObj.s = 0;
  749. cellObj.isBlank = true;
  750. rows[i - 1].items.push(cellObj);
  751. }
  752. }
  753. // 2. then fill up the cell style-ids and values
  754. let rowIdx1 = 0;
  755. let colIdx1 = 0;
  756. let rowIdx2 = 0;
  757. let colIdx2 = 0;
  758. // let colIdxStr = '';
  759. for (let cIdx = 0; cIdx < theShtData.cells.length; cIdx++) {
  760. const styleIdx = private_getStyleId(theShtData.cells[cIdx]);
  761. rowIdx1 = theYPos.indexOf(theShtData.cells[cIdx][JV.PROP_AREA][JV.PROP_TOP]);
  762. colIdx1 = xPos.indexOf(theShtData.cells[cIdx][JV.PROP_AREA][JV.PROP_LEFT]);
  763. let cellObj = rows[rowIdx1 - 1].items[colIdx1 - 1];
  764. cellObj.s = styleIdx;
  765. cellObj.isBlank = false;
  766. if (!(strUtil.isEmptyString(theShtData.cells[cIdx][JV.PROP_VALUE]))) {
  767. const valIdx = private_getSharedStrIdx(theShtData.cells[cIdx][JV.PROP_VALUE]);
  768. cellObj.v = valIdx;
  769. }
  770. rowIdx2 = theYPos.indexOf(theShtData.cells[cIdx][JV.PROP_AREA][JV.PROP_BOTTOM]);
  771. colIdx2 = xPos.indexOf(theShtData.cells[cIdx][JV.PROP_AREA][JV.PROP_RIGHT]);
  772. if ((rowIdx2 - rowIdx1 > 1) || (colIdx2 - colIdx1 > 1)) {
  773. for (let i = 0; i < rowIdx2 - rowIdx1; i++) {
  774. for (let j = 0; j < colIdx2 - colIdx1; j++) {
  775. if (i === 0 && j === 0) continue;
  776. cellObj = rows[rowIdx1 - 1 + i].items[colIdx1 - 1 + j];
  777. cellObj.s = styleIdx;
  778. cellObj.isBlank = true;
  779. }
  780. }
  781. }
  782. }
  783. // 3. then fill up rst
  784. for (let i = 0; i < rows.length; i++) {
  785. rst.push('<row r="' + (i + 1 + offsetY) + '" spans="1:' + spanX + '" ht="' + rows[i].height + '" customHeight="1">');
  786. for (let j = 0; j < rows[i].items.length; j++) {
  787. const cellObj = rows[i].items[j];
  788. if (cellObj.v === undefined) {
  789. rst.push('<c r="' + cellObj.r + '" s="' + cellObj.s + '"/>');
  790. } else {
  791. rst.push('<c r="' + cellObj.r + '" s="' + cellObj.s + '" t="s">');
  792. rst.push('<v>' + cellObj.v + '</v>');
  793. rst.push('</c>');
  794. }
  795. }
  796. rst.push('</row>');
  797. }
  798. // 4. maybe need to dispose the memory
  799. // ...
  800. };
  801. if (sheetData) {
  802. // current sheet data
  803. currentPageMergePos = sheetData[JV.PAGE_SPECIAL_MERGE_POS];
  804. currentMergeBorder = sheetData[JV.PROP_PAGE_MERGE_BORDER];
  805. self_setDataEx(sheetData, yPos, 0);
  806. } else {
  807. // total data in one sheet
  808. let cnt = 0;
  809. for (let i = 0; i < pageData.items.length; i++) {
  810. const shtItemData = pageData.items[i];
  811. currentPageMergePos = shtItemData[JV.PAGE_SPECIAL_MERGE_POS];
  812. currentMergeBorder = shtItemData[JV.PROP_PAGE_MERGE_BORDER];
  813. const tmpPos = yMultiPos[i];
  814. cellIdx = 0;
  815. self_setDataEx(shtItemData, tmpPos, cnt);
  816. cnt += tmpPos.length - 2;
  817. }
  818. }
  819. rst.push('</sheetData>');
  820. };
  821. private_pre_analyze_pos();
  822. rst.push(dftHeadXml + '\r\n');
  823. rst.push('<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">');
  824. const colStr = private_getCellIdxStr(xPos.length - 3);
  825. rst.push('<dimension ref="A1:' + colStr + '' + yPos.length + '"/>');
  826. rst.push('<sheetViews><sheetView tabSelected="1" workbookViewId="0">');
  827. // rst.push('<selection sqref="A1:' + colStr + '1"/>');
  828. rst.push('<selection sqref="A1:A1"/>');
  829. rst.push('</sheetView></sheetViews>');
  830. rst.push('<sheetFormatPr defaultRowHeight="13.5"/>');
  831. private_setCols();
  832. private_setSheetData();
  833. private_setMergedCells();
  834. rst.push('<phoneticPr fontId="1" type="noConversion"/>');
  835. // rst.push('<pageMargins left="0.315" right="0.215" top="0.315" bottom="0.315" header="0" footer="0"/>');
  836. rst.push('<pageMargins left="' + (parseFloat(pageData[JV.NODE_PAGE_INFO][JV.NODE_MARGINS][JV.PROP_LEFT]) * 0.39375) +
  837. '" right="0.215" top="0.315" bottom="0.315" header="0" footer="0"/>');
  838. const paperSizeIdx = JV.PAGES_SIZE_STR.indexOf(paperSize);
  839. let pStr = '';
  840. if (paperSizeIdx >= 0) {
  841. pStr = 'paperSize="' + JV.PAGES_SIZE_IDX[paperSizeIdx] + '"';
  842. }
  843. let orientationStr = (pageData[JV.NODE_PAGE_INFO][JV.NODE_PAGE_SIZE][0] > pageData[JV.NODE_PAGE_INFO][JV.NODE_PAGE_SIZE][1]) ? 'landscape' : 'portrait';
  844. if (currentPageMergePos) {
  845. orientationStr = (currentPageMergePos[JV.NODE_PAGE_SIZE][0] > currentPageMergePos[JV.NODE_PAGE_SIZE][1]) ? 'landscape' : 'portrait';
  846. }
  847. rst.push('<pageSetup ' + pStr + ' fitToWidth="0" fitToHeight="0" orientation="' + orientationStr + '" />');
  848. rst.push('<headerFooter alignWithMargins="0"/>');
  849. if (hasSignature) {
  850. rst.push('<drawing r:id="rId' + (sheetIdx + 1) + '"/>');
  851. }
  852. rst.push('</worksheet>');
  853. return rst;
  854. }
  855. function writeSheetRels(sheetIdx) {
  856. const rst = [];
  857. rst.push('<?xml version="1.0" encoding="UTF-8" standalone="yes"?>');
  858. rst.push('<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">');
  859. rst.push('<Relationship Id="rId' + (sheetIdx + 1) + '" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing" Target="../drawings/drawing' + (sheetIdx + 1) + '.xml"/>');
  860. rst.push('</Relationships>');
  861. return rst;
  862. }
  863. function writeImage(path, pic, baseDir) {
  864. let rst = null;
  865. if (pic) {
  866. // 这里pic的数据就是base64的,不能是其他
  867. rst = base64ToStream(pic);
  868. } else if (path) {
  869. const filePath = baseDir + '/app' + path;
  870. rst = fs.readFileSync(filePath);
  871. }
  872. return rst;
  873. }
  874. function writeDrawings(pageData, signKeyArr, signPathArr, isSinglePage) {
  875. const rst = [];
  876. let sheetIdx = 0;
  877. if (isSinglePage) {
  878. rst.push(writeDrawing(pageData, null, signKeyArr, signPathArr, sheetIdx));
  879. } else {
  880. for (let i = 0; i < pageData.items.length; i++) {
  881. rst.push(writeDrawing(pageData, pageData.items[i], signKeyArr, signPathArr, sheetIdx));
  882. sheetIdx++;
  883. }
  884. }
  885. return rst;
  886. }
  887. function writeDrawing(pageData, sheetData, signKeyArr, signPathArr, sheetIdx) {
  888. //
  889. }
  890. function writeDrawingsRels(amt) {
  891. const rst = [];
  892. rst.push('<?xml version="1.0" encoding="UTF-8" standalone="yes"?>');
  893. rst.push('<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">');
  894. for (let idx = 0; idx < amt; idx++) {
  895. rst.push('<Relationship Id="rId' + (idx + 1) + '" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="../media/image' + (idx + 1) + '.png"/>');
  896. }
  897. rst.push('</Relationships>');
  898. return rst;
  899. }
  900. function mergeProperties(orgObj, newObj) {
  901. const orgPropArr = [];
  902. const newPropArr = [];
  903. for (const p in orgObj) {
  904. orgPropArr.push(p);
  905. }
  906. for (const p in newObj) {
  907. newPropArr.push(p);
  908. }
  909. for (let i = 0; i < newPropArr.length; i++) {
  910. if (orgPropArr.indexOf(newPropArr[i]) < 0) {
  911. orgObj[newPropArr[i]] = newObj[newPropArr[i]];
  912. }
  913. }
  914. }
  915. function checkAndSetSignatureCache(pageData, signKeyArr, signPathArr) {
  916. // 备注:电子签名是以图形的方式处理,一页可以有多个签名,多页的签名基本是引用同样的图片,在这里先处理一下,后期统一引用。
  917. // 另:以后的图片(在电子签名(signature_cells)以外的图片)会单独处理(如计算图等)
  918. let rst = false;
  919. for (const page of pageData.items) {
  920. if (page[JV.PROP_SIGNATURE_CELLS] && page[JV.PROP_SIGNATURE_CELLS].length > 0) {
  921. for (const signature of page[JV.PROP_SIGNATURE_CELLS]) {
  922. if (signKeyArr.indexOf(signature.signature_name) < 0) {
  923. signKeyArr.push(signature.signature_name);
  924. const signPath = { path: null, pic: null };
  925. signPathArr.push(signPath);
  926. if (signature.pic) {
  927. signPath.pic = signature.pic;
  928. rst = true;
  929. } else if (signature.path) {
  930. signPath.path = signature.path;
  931. rst = true;
  932. }
  933. }
  934. }
  935. }
  936. }
  937. return rst;
  938. }
  939. function base64ToStream(dataurl) {
  940. // 将base64转换为流
  941. const arr = dataurl.split(',');
  942. const bstr = atob(arr[1]);
  943. let n = bstr.length;
  944. const u8arr = new Uint8Array(n);
  945. while (n--) {
  946. u8arr[n] = bstr.charCodeAt(n);
  947. }
  948. return u8arr;
  949. }
  950. module.exports = {
  951. exportExcel: function(pageData, paperSize, fName, options, custSheetNames, custSheetMergeBands, baseDir, callback) {
  952. const rptOptions = ({ singlePage: false, fileName: 'report' });
  953. if (options === 'true' || options === true) {
  954. rptOptions.singlePage = true;
  955. }
  956. const isSinglePage = rptOptions.singlePage;
  957. const sheets = [];
  958. const signKeyArr = [];
  959. const signPathArr = [];
  960. // const hasSignature = checkAndSetSignatureCache(pageData, signKeyArr, signPathArr);
  961. const hasSignature = false;
  962. if (isSinglePage) {
  963. sheets.push({ sheetName: '全部页' });
  964. } else {
  965. if (custSheetNames && custSheetNames.length === pageData.items.length) {
  966. for (let i = 0; i < pageData.items.length; i++) {
  967. sheets.push({ sheetName: custSheetNames[i] });
  968. }
  969. } else {
  970. for (let i = 0; i < pageData.items.length; i++) {
  971. sheets.push({ sheetName: '第' + (i + 1) + '页' });
  972. }
  973. }
  974. }
  975. // 1.
  976. let file = '[Content_Types].xml';
  977. let data = writeContentTypes(sheets, isSinglePage, hasSignature);
  978. const zip = new JSZip();
  979. zip.file(file, data.join(''), { compression: 'DEFLATE' });
  980. // 2.
  981. const zip_rels = zip.folder('_rels');
  982. file = '.rels';
  983. data = writeRootRels();
  984. zip_rels.file(file, data.join(''), { compression: 'DEFLATE' });
  985. // 3.
  986. const zip_docProps = zip.folder('docProps');
  987. file = 'app.xml';
  988. data = writeApp(sheets, isSinglePage);
  989. zip_docProps.file(file, data.join(''), { compression: 'DEFLATE' });
  990. file = 'core.xml';
  991. data = writeCore();
  992. zip_docProps.file(file, data.join(''), { compression: 'DEFLATE' });
  993. // 4.
  994. const zip_xl = zip.folder('xl');
  995. file = 'workbook.xml';
  996. data = writeXlWorkBook(sheets, isSinglePage);
  997. zip_xl.file(file, data.join(''), { compression: 'DEFLATE' });
  998. const zip_rels2 = zip_xl.folder('_rels');
  999. file = 'workbook.xml.rels';
  1000. data = writeXlRels(sheets, isSinglePage);
  1001. zip_rels2.file(file, data.join(''), { compression: 'DEFLATE' });
  1002. // 5.
  1003. const zip_theme = zip_xl.folder('theme');
  1004. file = 'theme1.xml';
  1005. data = writeTheme();
  1006. zip_theme.file(file, data, { compression: 'DEFLATE' });
  1007. if (hasSignature) {
  1008. // 5.1
  1009. const zip_media = zip_xl.folder('media');
  1010. for (let signIdx = 0; signIdx < signPathArr.length; signIdx++) {
  1011. data = writeImage(signPathArr[signIdx].path, signPathArr[signIdx].pic, baseDir);
  1012. file = 'image' + (signIdx + 1) + '.png';
  1013. zip_media.file(file, data, { compression: 'DEFLATE' });
  1014. }
  1015. // 5.2
  1016. const zip_drawings = zip_xl.folder('drwaings');
  1017. data = writeDrawings(pageData, signKeyArr, signPathArr);
  1018. file = 'drawing1.xml.rels';
  1019. zip_drawings.file(file, data, { compression: 'DEFLATE' });
  1020. // 5.3
  1021. const zip_drawings_rels = zip_drawings.folder('_rels');
  1022. data = writeDrawingsRels(signPathArr.length);
  1023. file = 'drawing1.xml.rels';
  1024. zip_drawings_rels.file(file, data, { compression: 'DEFLATE' });
  1025. }
  1026. // 6.
  1027. const zip_worksheets = zip_xl.folder('worksheets');
  1028. const sharedStrList = [];
  1029. const stylesObj = {};
  1030. data = writeSheets(pageData, paperSize, sharedStrList, stylesObj, isSinglePage, custSheetMergeBands, hasSignature);
  1031. if (isSinglePage) {
  1032. for (let i = 0; i < 1; i++) {
  1033. file = 'sheet' + (i + 1) + '.xml';
  1034. zip_worksheets.file(file, data[i].join(''), { compression: 'DEFLATE' });
  1035. }
  1036. } else {
  1037. for (let i = 0; i < data.length; i++) {
  1038. file = 'sheet' + (i + 1) + '.xml';
  1039. zip_worksheets.file(file, data[i].join(''), { compression: 'DEFLATE' });
  1040. }
  1041. }
  1042. // 7.
  1043. if (hasSignature) {
  1044. const zip_worksheets_rels = zip_xl.folder('_rels');
  1045. if (isSinglePage) {
  1046. for (let i = 0; i < 1; i++) {
  1047. data = writeSheetRels(0);
  1048. file = 'sheet' + (i + 1) + '.xml.rels';
  1049. zip_worksheets_rels.file(file, data[i].join(''), { compression: 'DEFLATE' });
  1050. }
  1051. } else {
  1052. for (let i = 0; i < data.length; i++) {
  1053. data = writeSheetRels(0);
  1054. file = 'sheet' + (i + 1) + '.xml.rels';
  1055. zip_worksheets_rels.file(file, data[i].join(''), { compression: 'DEFLATE' });
  1056. }
  1057. }
  1058. }
  1059. file = 'sharedStrings.xml';
  1060. data = writeSharedString(sharedStrList);
  1061. zip_xl.file(file, data.join(''), { compression: 'DEFLATE' });
  1062. file = 'styles.xml';
  1063. data = writeStyles(stylesObj, hasSignature);
  1064. zip_xl.file(file, data.join(''), { compression: 'DEFLATE' });
  1065. if (fName) {
  1066. // let newName = '' + (new Date()).valueOf();
  1067. const newName = uuidV1();
  1068. // console.log('current path: ' + __dirname);
  1069. // const filePath = this.app.baseDir + '/app/public/download/';
  1070. zip.generateNodeStream({ type: 'nodebuffer', streamFiles: true })
  1071. .pipe(fs.createWriteStream(__dirname.slice(0, __dirname.length - 13) + '/public/download/' + newName + '.xlsx'))
  1072. .on('finish', function() {
  1073. // JSZip generates a readable stream with a "end" event,
  1074. // but is piped here in a writable stream which emits a "finish" event.
  1075. console.log(newName + '.xlsx was written.');
  1076. if (callback) callback(null, newName);
  1077. });
  1078. } else {
  1079. // return zip.generateNodeStream({type:'nodebuffer',streamFiles:true});
  1080. return zip;
  1081. }
  1082. },
  1083. exportExcelInOneBook: function(pageDataArray, paperSize, fName, baseDir, callback) {
  1084. const me = this;
  1085. const newPageData = {};
  1086. // 1. 重新编排一下数据,把一份报表的pageData合并到一起作为一个Sheet输出(需要重新调整数据纵向坐标),多份报表数据就形成多个Sheet
  1087. // -- 简单来说,就是重新包装数据
  1088. try {
  1089. // 1.1 newPageData外围属性
  1090. const newContrl = {};
  1091. const newFont = {};
  1092. const newStyle = {};
  1093. const custMergeBands = [];
  1094. for (let i = 0; i < pageDataArray.length; i++) {
  1095. mergeProperties(newContrl, pageDataArray[i][JV.NODE_CONTROL_COLLECTION]);
  1096. mergeProperties(newFont, pageDataArray[i][JV.NODE_FONT_COLLECTION]);
  1097. mergeProperties(newStyle, pageDataArray[i][JV.NODE_STYLE_COLLECTION]);
  1098. }
  1099. newPageData[JV.NODE_CONTROL_COLLECTION] = newContrl;
  1100. newPageData[JV.NODE_FONT_COLLECTION] = newFont;
  1101. newPageData[JV.NODE_STYLE_COLLECTION] = newStyle;
  1102. newPageData[JV.NODE_PAGE_INFO] = pageDataArray[0][JV.NODE_PAGE_INFO];
  1103. newPageData[JV.BAND_PROP_MERGE_BAND] = pageDataArray[0][JV.BAND_PROP_MERGE_BAND];
  1104. // 1.2 重新设置pageDataArray的各个cell的Top/Bottom坐标
  1105. const sheetNames = [];
  1106. const newPagePos = [];
  1107. for (let i = 0; i < pageDataArray.length; i++) {
  1108. let offsetY = 0;
  1109. const mergeBand = {};
  1110. custMergeBands.push(pageDataArray[i][JV.BAND_PROP_MERGE_BAND]);
  1111. // 备注:不同的报表有可能有不同的边框,如封面表就是无边框的
  1112. mergeBand[JV.PROP_LEFT] = [];
  1113. mergeBand[JV.PROP_RIGHT] = [];
  1114. mergeBand[JV.PROP_TOP] = [];
  1115. mergeBand[JV.PROP_BOTTOM] = [];
  1116. newPagePos.push(mergeBand);
  1117. mergeBand[JV.PROP_LEFT].push(pageDataArray[i][JV.BAND_PROP_MERGE_BAND][JV.PROP_LEFT]);
  1118. mergeBand[JV.PROP_RIGHT].push(pageDataArray[i][JV.BAND_PROP_MERGE_BAND][JV.PROP_RIGHT]);
  1119. sheetNames.push(pageDataArray[i][JV.NODE_PAGE_INFO][JV.NODE_MAIN_INFO_RPT_NAME]);
  1120. for (let j = 0; j < pageDataArray[i].items.length; j++) {
  1121. let maxY = 0;
  1122. let minY = 100000;
  1123. if (pageDataArray[i].items[j][JV.PAGE_SPECIAL_MERGE_POS]) {
  1124. let pos = pageDataArray[i].items[j][JV.PAGE_SPECIAL_MERGE_POS][JV.PROP_TOP][0] + offsetY;
  1125. mergeBand[JV.PROP_TOP].push(pos);
  1126. pos = pageDataArray[i].items[j][JV.PAGE_SPECIAL_MERGE_POS][JV.PROP_BOTTOM][0] + offsetY;
  1127. mergeBand[JV.PROP_BOTTOM].push(pos);
  1128. } else if (pageDataArray[i].items[j][JV.PROP_PAGE_MERGE_BORDER]) {
  1129. let pos = pageDataArray[i].items[j][JV.PROP_PAGE_MERGE_BORDER][JV.PROP_TOP] + offsetY;
  1130. mergeBand[JV.PROP_TOP].push(pos);
  1131. pos = pageDataArray[i].items[j][JV.PROP_PAGE_MERGE_BORDER][JV.PROP_BOTTOM] + offsetY;
  1132. mergeBand[JV.PROP_BOTTOM].push(pos);
  1133. } else {
  1134. mergeBand[JV.PROP_TOP].push(pageDataArray[i][JV.BAND_PROP_MERGE_BAND][JV.PROP_TOP] + offsetY);
  1135. mergeBand[JV.PROP_BOTTOM].push(pageDataArray[i][JV.BAND_PROP_MERGE_BAND][JV.PROP_BOTTOM] + offsetY);
  1136. }
  1137. for (let k = 0; k < pageDataArray[i].items[j].cells.length; k++) {
  1138. if (maxY < pageDataArray[i].items[j].cells[k][JV.PROP_AREA][JV.PROP_BOTTOM]) {
  1139. maxY = pageDataArray[i].items[j].cells[k][JV.PROP_AREA][JV.PROP_BOTTOM];
  1140. }
  1141. if (minY > pageDataArray[i].items[j].cells[k][JV.PROP_AREA][JV.PROP_TOP]) {
  1142. minY = pageDataArray[i].items[j].cells[k][JV.PROP_AREA][JV.PROP_TOP];
  1143. }
  1144. pageDataArray[i].items[j].cells[k][JV.PROP_AREA][JV.PROP_BOTTOM] += offsetY;
  1145. pageDataArray[i].items[j].cells[k][JV.PROP_AREA][JV.PROP_TOP] += offsetY;
  1146. }
  1147. const bottomGap = Math.round( (pageDataArray[i][JV.NODE_PAGE_INFO][JV.NODE_PAGE_SIZE][1] - parseFloat(pageDataArray[i][JV.NODE_PAGE_INFO][JV.NODE_MARGINS][JV.PROP_BOTTOM]) / 2.54 ) * DPI) - maxY;
  1148. offsetY += (maxY - minY);
  1149. if (bottomGap > 10) {
  1150. offsetY += (bottomGap - 10);
  1151. }
  1152. }
  1153. }
  1154. // 2. newPageData的items属性
  1155. newPageData.items = [];
  1156. for (let i = 0; i < pageDataArray.length; i++) {
  1157. const pageItem = {};
  1158. pageItem[JV.PROP_PAGE_SEQ] = i + 1;
  1159. pageItem[JV.PROP_CELLS] = [];
  1160. for (let j = 0; j < pageDataArray[i].items.length; j++) {
  1161. for (let k = 0; k < pageDataArray[i].items[j].cells.length; k++) {
  1162. pageItem[JV.PROP_CELLS].push(pageDataArray[i].items[j].cells[k]);
  1163. }
  1164. }
  1165. newPagePos[i][JV.NODE_PAGE_SIZE] = pageDataArray[i][JV.NODE_PAGE_INFO][JV.NODE_PAGE_SIZE];
  1166. pageItem[JV.PAGE_SPECIAL_MERGE_POS] = newPagePos[i];
  1167. newPageData.items.push(pageItem);
  1168. }
  1169. // 3. everything is ok, then call me
  1170. me.exportExcel(newPageData, paperSize, fName, 'false', sheetNames, custMergeBands, baseDir, callback);
  1171. // fsUtil.writeObjToFile(newPageData, 'D:/GitHome/ConstructionOperation/tmp/combinedHeader.js');
  1172. } catch (e) {
  1173. console.log(e);
  1174. }
  1175. },
  1176. };