rpt_excel_util.js 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792
  1. /**
  2. * Created by Tony on 2017/4/1.
  3. */
  4. let JV = require('../rpt_component/jpc_value_define');
  5. let fs = require('fs');
  6. let JSZip = require("jszip");
  7. let strUtil = require('../../../public/stringUtil');
  8. let jpcCmnHelper = require('../rpt_component/helper/jpc_helper_common');
  9. let DPI = jpcCmnHelper.getScreenDPI()[0];
  10. const dftHeadXml = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>';
  11. function writeContentTypes(sheets, isSinglePage) {
  12. let rst = [];
  13. rst.push(dftHeadXml + '\r\n');
  14. rst.push('<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">');
  15. //...
  16. rst.push('<Override PartName="/xl/theme/theme1.xml" ContentType="application/vnd.openxmlformats-officedocument.theme+xml"/>');
  17. rst.push('<Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/>');
  18. rst.push('<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>');
  19. rst.push('<Default Extension="xml" ContentType="application/xml"/>');
  20. rst.push('<Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>');
  21. rst.push('<Override PartName="/docProps/app.xml" ContentType="application/vnd.openxmlformats-officedocument.extended-properties+xml"/>');
  22. rst.push('<Override PartName="/xl/sharedStrings.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml"/>');
  23. if (isSinglePage) {
  24. rst.push('<Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>')
  25. } else {
  26. for (let i = 0; i < sheets.length; i++) {
  27. rst.push('<Override PartName="/xl/worksheets/sheet' + (i + 1) + '.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>')
  28. }
  29. }
  30. rst.push('<Override PartName="/docProps/core.xml" ContentType="application/vnd.openxmlformats-package.core-properties+xml"/>');
  31. rst.push('</Types>');
  32. return rst;
  33. }
  34. function writeRootRels(){
  35. let rst = [];
  36. rst.push(dftHeadXml + '\r\n');
  37. rst.push('<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">');
  38. rst.push('<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/>');
  39. rst.push('<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties" Target="docProps/core.xml"/>');
  40. rst.push('<Relationship Id="rId3" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties" Target="docProps/app.xml"/>');
  41. rst.push('</Relationships>');
  42. return rst;
  43. }
  44. function writeApp(sheets, isSinglePage) {
  45. let rst = [];
  46. rst.push(dftHeadXml + '\r\n');
  47. rst.push('<Properties xmlns="http://schemas.openxmlformats.org/officeDocument/2006/extended-properties" xmlns:vt="http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes">');
  48. rst.push('<Application>Microsoft Excel</Application>');
  49. rst.push('<DocSecurity>0</DocSecurity>');
  50. rst.push('<ScaleCrop>false</ScaleCrop>');
  51. rst.push('<HeadingPairs>');
  52. rst.push('<vt:vector size="2" baseType="variant">');
  53. rst.push('<vt:variant><vt:lpstr>工作表</vt:lpstr></vt:variant>');
  54. if (isSinglePage) rst.push('<vt:variant><vt:i4>1</vt:i4></vt:variant>')
  55. else rst.push('<vt:variant><vt:i4>' + sheets.length + '</vt:i4></vt:variant>');
  56. rst.push('</vt:vector>');
  57. rst.push('</HeadingPairs>');
  58. rst.push('<TitlesOfParts>');
  59. if (isSinglePage) {
  60. rst.push('<vt:vector size="1" baseType="lpstr">');
  61. rst.push('<vt:lpstr>' + sheets[0].sheetName + '</vt:lpstr>')
  62. } else {
  63. rst.push('<vt:vector size="' + sheets.length + '" baseType="lpstr">');
  64. for (let i = 0; i < sheets.length; i++) {
  65. rst.push('<vt:lpstr>' + sheets[i].sheetName + '</vt:lpstr>')
  66. }
  67. }
  68. rst.push('</vt:vector>');
  69. rst.push('</TitlesOfParts>');
  70. rst.push('<Company>SmartCost</Company>');
  71. rst.push('<LinksUpToDate>false</LinksUpToDate>');
  72. rst.push('<SharedDoc>false</SharedDoc>');
  73. rst.push('<HyperlinksChanged>false</HyperlinksChanged>');
  74. rst.push('<AppVersion>12.0000</AppVersion>');
  75. //rst.push('');
  76. rst.push('</Properties>');
  77. return rst;
  78. }
  79. function writeCore() {
  80. let rst = [];
  81. p_fillZero = function(val){
  82. let rst = val;
  83. if (val < 10) {
  84. rst = '0' + val;
  85. }
  86. return rst;
  87. };
  88. rst.push(dftHeadXml + '\r\n');
  89. 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">');
  90. rst.push('<dc:creator>SmartCost</dc:creator>');
  91. rst.push('<cp:lastModifiedBy>SmartCost</cp:lastModifiedBy>');
  92. let dt = new Date(), dtStr = dt.getFullYear() + '-' + p_fillZero(dt.getMonth()+1) + '-' + p_fillZero(dt.getDate()) + 'T' +
  93. p_fillZero(dt.getHours()) + ':' + p_fillZero(dt.getMinutes()) + ':' + p_fillZero(dt.getSeconds()) + 'Z';
  94. rst.push('<dcterms:created xsi:type="dcterms:W3CDTF">' + dtStr + '</dcterms:created>');
  95. rst.push('<dcterms:modified xsi:type="dcterms:W3CDTF">' + dtStr + '</dcterms:modified>');
  96. //rst.push('');
  97. rst.push('</cp:coreProperties>');
  98. return rst;
  99. }
  100. function writeXlWorkBook(sheets, isSinglePage){
  101. let rst = [];
  102. rst.push(dftHeadXml + '\r\n');
  103. rst.push('<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">');
  104. rst.push('<fileVersion appName="xl" lastEdited="4" lowestEdited="4" rupBuild="4505"/>');
  105. rst.push('<workbookPr defaultThemeVersion="124226"/>');
  106. rst.push('<bookViews><workbookView xWindow="360" yWindow="345" windowWidth="14655" windowHeight="4305"/></bookViews>');
  107. rst.push('<sheets>');
  108. if (isSinglePage) {
  109. rst.push('<sheet name="' + sheets[0].sheetName + '" sheetId="1" r:id="rId1"/>');
  110. } else {
  111. for (let i = 0; i < sheets.length; i++) {
  112. rst.push('<sheet name="' + sheets[i].sheetName + '" sheetId="' + (i + 1) + '" r:id="rId' + (i + 1) + '"/>');
  113. }
  114. }
  115. rst.push('</sheets>');
  116. rst.push('<calcPr calcId="124519"/>');
  117. //rst.push('');
  118. rst.push('</workbook>');
  119. return rst;
  120. }
  121. function writeXlRels(sheets, isSinglePage){
  122. let rst = [], idx = 1;
  123. rst.push(dftHeadXml + '\r\n');
  124. rst.push('<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">');
  125. if (isSinglePage) {
  126. rst.push('<Relationship Id="rId' + idx + '" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/>')
  127. idx++;
  128. } else {
  129. for (let i = 0; i < sheets.length; i++) {
  130. rst.push('<Relationship Id="rId' + idx + '" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet' + (i + 1) + '.xml"/>')
  131. idx++;
  132. }
  133. }
  134. rst.push('<Relationship Id="rId' + idx + '" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme" Target="theme/theme1.xml"/>');
  135. idx++;
  136. rst.push('<Relationship Id="rId' + idx + '" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>');
  137. idx++;
  138. rst.push('<Relationship Id="rId' + idx + '" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings" Target="sharedStrings.xml"/>');
  139. //rst.push('');
  140. rst.push('</Relationships>');
  141. return rst;
  142. }
  143. function writeTheme(){
  144. let rst = fs.readFileSync(__dirname + '/excel_base_files/theme1.xml', 'utf8', 'r');
  145. return rst;
  146. }
  147. function writeStyles(stylesObj){
  148. let rst = [];
  149. rst.push(dftHeadXml + '\r\n');
  150. rst.push('<styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">');
  151. //1. push fonts
  152. rst.push('<fonts count="' + stylesObj.fonts.length + '">')
  153. for (let i = 0; i < stylesObj.fonts.length; i++) {
  154. let font = stylesObj.fonts[i];
  155. rst.push('<font>');
  156. if (strUtil.convertStrToBoolean(font[JV.FONT_PROPS[3]])) {
  157. rst.push('<b/>');
  158. }
  159. rst.push('<sz val="' + font.size + '"/>');
  160. rst.push('<color indexed="' + font.colorIdx + '"/>');
  161. rst.push('<name val="' + font[JV.FONT_PROPS[0]] + '"/>');
  162. rst.push('<charset val="' + font.charset + '"/>');
  163. rst.push('</font>');
  164. }
  165. rst.push('</fonts>');
  166. //2. push default fills
  167. rst.push('<fills count="2"><fill><patternFill patternType="none" /></fill><fill><patternFill patternType="gray125" /></fill></fills>');
  168. //3. push borders
  169. rst.push('<borders count="' + stylesObj.borders.length + '">')
  170. private_setBorder = function(border, borderDirection) {
  171. if (border[borderDirection][JV.PROP_LINE_WEIGHT] == 0) {
  172. rst.push('<' + borderDirection.toLowerCase() + '/>');
  173. } else {
  174. let bW = 'thin';
  175. if (border[borderDirection][JV.PROP_LINE_WEIGHT] == 2) bW = 'medium';
  176. if (border[borderDirection][JV.PROP_LINE_WEIGHT] > 2) bW = 'thick';
  177. rst.push('<' + borderDirection.toLowerCase() + ' style="' + bW + '">' + '<color indexed="64"/>' + '</' + borderDirection.toLowerCase() + '>');
  178. }
  179. };
  180. for (let i = 0; i < stylesObj.borders.length; i++) {
  181. let border = stylesObj.borders[i];
  182. rst.push('<border>');
  183. private_setBorder(border, JV.PROP_LEFT);
  184. private_setBorder(border, JV.PROP_RIGHT);
  185. private_setBorder(border, JV.PROP_TOP);
  186. private_setBorder(border, JV.PROP_BOTTOM);
  187. rst.push('<diagonal />');
  188. rst.push('</border>');
  189. }
  190. rst.push('</borders>');
  191. //4. push cellStyleXfs
  192. rst.push('<cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"><alignment vertical="center"/></xf></cellStyleXfs>');
  193. //5. push cellXfs
  194. rst.push('<cellXfs count="' + stylesObj.cellXfs.length + '">');
  195. for (let i = 0; i < stylesObj.cellXfs.length; i++) {
  196. let excelStyle = stylesObj.cellXfs[i];
  197. rst.push('<xf numFmtId="0" fontId="' + excelStyle.fontId + '" fillId="0" borderId="' + excelStyle.borderId + '" xfId="0">');
  198. let alignStr = '<alignment horizontal="' + excelStyle[JV.CONTROL_PROPS[2]] + '" vertical="' + excelStyle[JV.CONTROL_PROPS[3]] + '"';
  199. if (strUtil.convertStrToBoolean(excelStyle[JV.CONTROL_PROPS[1]])) {
  200. alignStr = alignStr + ' shrinkToFit="1"';
  201. }
  202. if (strUtil.convertStrToBoolean(excelStyle[JV.CONTROL_PROPS[4]])) {
  203. alignStr = alignStr + ' wrapText="1"';
  204. }
  205. alignStr = alignStr + '/>';
  206. rst.push(alignStr);
  207. rst.push('</xf>');
  208. }
  209. rst.push('</cellXfs>');
  210. //6. others (xfl style / dxfs / tableStyles)
  211. rst.push('<cellStyles count="1"><cellStyle name="常规" xfId="0" builtinId="0"/></cellStyles>');
  212. rst.push('<dxfs count="0"/>');
  213. rst.push('<tableStyles count="0" defaultTableStyle="TableStyleMedium9" defaultPivotStyle="PivotStyleLight16"/>');
  214. rst.push('</styleSheet>');
  215. return rst;
  216. }
  217. function writeSharedString(sharedStrList){
  218. let rst = [];
  219. if (sharedStrList && sharedStrList.length > 0) {
  220. rst.push(dftHeadXml + '\r\n');
  221. rst.push('<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" count="' + sharedStrList.length + '" uniqueCount="' + sharedStrList.length + '">');
  222. for (let i = 0; i < sharedStrList.length; i++) {
  223. //rst.push('<si><t>' + sharedStrList[i] + '</t></si>');
  224. if (typeof sharedStrList[i] === 'string') {
  225. rst.push('<si><t>' + sharedStrList[i].replace('|','\r\n') + '</t></si>');
  226. } else {
  227. rst.push('<si><t>' + sharedStrList[i] + '</t></si>');
  228. }
  229. }
  230. rst.push('</sst>');
  231. }
  232. return rst;
  233. }
  234. function writeSheets(pageData, paperSize, sharedStrList, stylesObj, isSinglePage){
  235. let rst = [];
  236. private_pushDftFont = function(){
  237. let font = {};
  238. if (!(stylesObj.fonts)) {
  239. stylesObj.fonts = [];
  240. }
  241. font[JV.FONT_PROPS[0]] = "宋体"; //font name
  242. font.size = 12;
  243. font.charset = 134;
  244. font.colorIdx = "8";
  245. stylesObj.fonts.push(font);
  246. };
  247. private_pushDftFont();
  248. if (isSinglePage) {
  249. rst.push(writeSheet(pageData, null, paperSize, sharedStrList, stylesObj));
  250. } else {
  251. for (let i = 0; i < pageData.items.length; i++) {
  252. rst.push(writeSheet(pageData, pageData.items[i], paperSize, sharedStrList, stylesObj));
  253. }
  254. }
  255. return rst;
  256. }
  257. function writeSheet(pageData, sheetData, paperSize, sharedStrList, stylesObj){
  258. let rst = [], xPos = [], yPos = [], yMultiPos = [], headerStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  259. let cacheBorderCell = {};
  260. private_pre_analyze_pos = function(){
  261. let cell, pos;
  262. self_analyze_sheet_pos = function (theShtData, theXPos, theYPos) {
  263. theShtData.cells.sort(function(cell1, cell2) {
  264. let rst = 0;
  265. if (cell1[JV.PROP_AREA][JV.PROP_TOP] > cell2[JV.PROP_AREA][JV.PROP_TOP]) {
  266. rst = 1;
  267. } else if (cell1[JV.PROP_AREA][JV.PROP_TOP] < cell2[JV.PROP_AREA][JV.PROP_TOP]) {
  268. rst = -1;
  269. } else {
  270. if (cell1[JV.PROP_AREA][JV.PROP_LEFT] > cell2[JV.PROP_AREA][JV.PROP_LEFT]) {
  271. rst = 1;
  272. } else if (cell1[JV.PROP_AREA][JV.PROP_LEFT] < cell2[JV.PROP_AREA][JV.PROP_LEFT]) {
  273. rst = -1;
  274. }
  275. }
  276. return rst;
  277. });
  278. for (let i = 0; i < theShtData.cells.length; i++) {
  279. cell = theShtData.cells[i];
  280. pos = cell[JV.PROP_AREA][JV.PROP_LEFT];
  281. if (theXPos.indexOf(pos) < 0) theXPos.push(pos);
  282. pos = cell[JV.PROP_AREA][JV.PROP_RIGHT];
  283. if (theXPos.indexOf(pos) < 0) theXPos.push(pos);
  284. pos = cell[JV.PROP_AREA][JV.PROP_TOP];
  285. if (theYPos.indexOf(pos) < 0) theYPos.push(pos);
  286. pos = cell[JV.PROP_AREA][JV.PROP_BOTTOM];
  287. if (theYPos.indexOf(pos) < 0) theYPos.push(pos);
  288. }
  289. };
  290. xPos.push(0);
  291. if (sheetData) {
  292. //current sheet data
  293. yPos.push(0);
  294. self_analyze_sheet_pos(sheetData, xPos, yPos);
  295. xPos.sort(private_array_sort);
  296. yPos.sort(private_array_sort);
  297. } else {
  298. //total data in one sheet
  299. for (let shtItemData of pageData.items) {
  300. let tmpPos = [];
  301. tmpPos.push(0);
  302. self_analyze_sheet_pos(shtItemData, xPos, tmpPos);
  303. tmpPos.sort(private_array_sort);
  304. yMultiPos.push(tmpPos);
  305. }
  306. xPos.sort(private_array_sort);
  307. yPos = yMultiPos[0];
  308. }
  309. };
  310. private_array_sort = function(i1, i2){
  311. let rst = 0;
  312. if (i1 > i2) {rst = 1} else
  313. if (i1 < i2) rst = -1;
  314. return rst;
  315. };
  316. private_getCellIdxStr = function(idx){
  317. let rst = 'A';
  318. if (idx < 26) {
  319. rst = headerStr[idx];
  320. } else if (idx < 26*26+26) {
  321. let ti = Math.floor(idx / 26), tj = idx % 26;
  322. rst = headerStr[ti - 1] + headerStr[tj];
  323. } else if (idx < 26*26*26+26) {
  324. let ti = Math.floor(idx / (26*26)), tj = Math.floor((idx - ti * 26*26) / 26), tk = idx % 26;
  325. rst = headerStr[ti - 1] + headerStr[tj-1] + headerStr[tk];
  326. }
  327. return rst;
  328. };
  329. private_getSharedStrIdx = function(val) {
  330. let rst = sharedStrList.indexOf(val);
  331. if (rst < 0) {
  332. sharedStrList.push(val);
  333. rst = sharedStrList.length - 1;
  334. }
  335. return rst;
  336. };
  337. private_getFontId = function(cell) {
  338. let rst = 0, hasFont = false;
  339. if (!(stylesObj.fonts)) {
  340. stylesObj.fonts = [];
  341. //for (let i = 0; i < sheetData.font_collection)
  342. }
  343. let sheetFont = pageData.font_collection[cell.font];
  344. for (let i = 0; i < stylesObj.fonts.length; i++) {
  345. let font = stylesObj.fonts[i];
  346. if (sheetFont) {
  347. if (font[JV.FONT_PROPS[0]] === sheetFont[JV.FONT_PROPS[0]] && font.size === Math.round(sheetFont[JV.FONT_PROPS[1]] * 3 / 4) && font[JV.FONT_PROPS[3]] == sheetFont[JV.FONT_PROPS[3]]) {
  348. hasFont = true;
  349. rst = i;
  350. break;
  351. }
  352. } else {
  353. break;
  354. }
  355. }
  356. if (!hasFont) {
  357. let font = {};
  358. font[JV.FONT_PROPS[0]] = sheetFont[JV.FONT_PROPS[0]]; //font name
  359. font.size = Math.round(sheetFont[JV.FONT_PROPS[1]] * 3 / 4);
  360. font.charset = 134;
  361. font.colorIdx = "8";
  362. font[JV.FONT_PROPS[3]] = sheetFont[JV.FONT_PROPS[3]]; //font bold
  363. stylesObj.fonts.push(font);
  364. rst = stylesObj.fonts.length - 1;
  365. }
  366. return rst;
  367. };
  368. private_checkBorder = function(cell, border, sheetBorder) {
  369. let rst = true, borderLineWidths = [], sheetBorderLineWidths = [];
  370. borderLineWidths.push(border[JV.PROP_LEFT][JV.PROP_LINE_WEIGHT]);
  371. borderLineWidths.push(border[JV.PROP_RIGHT][JV.PROP_LINE_WEIGHT]);
  372. borderLineWidths.push(border[JV.PROP_TOP][JV.PROP_LINE_WEIGHT]);
  373. borderLineWidths.push(border[JV.PROP_BOTTOM][JV.PROP_LINE_WEIGHT]);
  374. if (sheetBorder[JV.PROP_LEFT] && sheetBorder[JV.PROP_LEFT][JV.PROP_LINE_WEIGHT]) {
  375. sheetBorderLineWidths.push(private_chkAndGetMergeLine(cell, sheetBorder, JV.PROP_LEFT));
  376. } else {
  377. sheetBorderLineWidths.push(0);
  378. }
  379. if (sheetBorder[JV.PROP_RIGHT] && sheetBorder[JV.PROP_RIGHT][JV.PROP_LINE_WEIGHT]) {
  380. sheetBorderLineWidths.push(private_chkAndGetMergeLine(cell, sheetBorder, JV.PROP_RIGHT));
  381. } else {
  382. sheetBorderLineWidths.push(0);
  383. }
  384. if (sheetBorder[JV.PROP_TOP] && sheetBorder[JV.PROP_TOP][JV.PROP_LINE_WEIGHT]) {
  385. sheetBorderLineWidths.push(private_chkAndGetMergeLine(cell, sheetBorder, JV.PROP_TOP));
  386. } else {
  387. sheetBorderLineWidths.push(0);
  388. }
  389. if (sheetBorder[JV.PROP_BOTTOM] && sheetBorder[JV.PROP_BOTTOM][JV.PROP_LINE_WEIGHT]) {
  390. sheetBorderLineWidths.push(private_chkAndGetMergeLine(cell, sheetBorder, JV.PROP_BOTTOM));
  391. } else {
  392. sheetBorderLineWidths.push(0);
  393. }
  394. for (let i = 0; i < 4; i++) {
  395. if (borderLineWidths[i] != sheetBorderLineWidths[i]) {
  396. rst = false;
  397. break;
  398. }
  399. }
  400. return rst;
  401. };
  402. private_chkAndGetMergeLine = function(cell, sheetBorder, borderStr) {
  403. let rst = sheetBorder[borderStr][JV.PROP_LINE_WEIGHT], mergeBorder = pageData[JV.BAND_PROP_MERGE_BAND];
  404. if (cell[JV.PROP_AREA][borderStr] == mergeBorder[borderStr]) {
  405. let destStyle = pageData[JV.NODE_STYLE_COLLECTION][mergeBorder[JV.PROP_STYLE][JV.PROP_ID]];
  406. rst = destStyle[borderStr][JV.PROP_LINE_WEIGHT];
  407. }
  408. return parseInt(rst);
  409. };
  410. private_getIniBorder = function() {
  411. let rst = {};
  412. rst[JV.PROP_LEFT] = {};
  413. rst[JV.PROP_LEFT][JV.PROP_LINE_WEIGHT] = 0;
  414. rst[JV.PROP_RIGHT] = {};
  415. rst[JV.PROP_RIGHT][JV.PROP_LINE_WEIGHT] = 0;
  416. rst[JV.PROP_TOP] = {};
  417. rst[JV.PROP_TOP][JV.PROP_LINE_WEIGHT] = 0;
  418. rst[JV.PROP_BOTTOM] = {};
  419. rst[JV.PROP_BOTTOM][JV.PROP_LINE_WEIGHT] = 0;
  420. return rst;
  421. };
  422. private_getBorderId = function(cell) {
  423. let rst = 0, hasBorder = false;
  424. if (!(stylesObj.borders)) {
  425. stylesObj.borders = [];
  426. }
  427. let sheetBorder = pageData[JV.NODE_STYLE_COLLECTION][cell.style];
  428. for (let i = 0; i < stylesObj.borders.length; i++) {
  429. let border = stylesObj.borders[i];
  430. if (private_checkBorder(cell, border, sheetBorder)) {
  431. hasBorder = true;
  432. rst = i;
  433. break;
  434. }
  435. }
  436. if (!hasBorder) {
  437. let border = private_getIniBorder();
  438. if (sheetBorder && sheetBorder[JV.PROP_LEFT]) {
  439. border[JV.PROP_LEFT][JV.PROP_LINE_WEIGHT] = private_chkAndGetMergeLine(cell, sheetBorder, JV.PROP_LEFT);
  440. }
  441. if (sheetBorder && sheetBorder[JV.PROP_RIGHT]) {
  442. border[JV.PROP_RIGHT][JV.PROP_LINE_WEIGHT] = private_chkAndGetMergeLine(cell, sheetBorder, JV.PROP_RIGHT);
  443. }
  444. if (sheetBorder && sheetBorder[JV.PROP_TOP]) {
  445. border[JV.PROP_TOP][JV.PROP_LINE_WEIGHT] = private_chkAndGetMergeLine(cell, sheetBorder, JV.PROP_TOP);
  446. }
  447. if (sheetBorder && sheetBorder[JV.PROP_BOTTOM]) {
  448. border[JV.PROP_BOTTOM][JV.PROP_LINE_WEIGHT] = private_chkAndGetMergeLine(cell, sheetBorder, JV.PROP_BOTTOM);
  449. }
  450. stylesObj.borders.push(border);
  451. rst = stylesObj.borders.length - 1;
  452. }
  453. return rst;
  454. };
  455. private_checkControl = function(cellControl, sheetControl) {
  456. let rst = true;
  457. for (let i = 0; i < JV.CONTROL_PROPS.length; i++) {
  458. if (cellControl[JV.CONTROL_PROPS[i]] != sheetControl[JV.CONTROL_PROPS[i]]) {
  459. rst = false;
  460. break;
  461. }
  462. }
  463. return rst;
  464. };
  465. private_getStyleId = function(cell) {
  466. let rst = 1, hasStyle = false;
  467. if (!(stylesObj.cellXfs)) stylesObj.cellXfs = [];
  468. let fontId = private_getFontId(cell);
  469. let borderId = private_getBorderId(cell);
  470. let cellControl = pageData[JV.NODE_CONTROL_COLLECTION][cell[JV.PROP_CONTROL]];
  471. for (let i = 0; i < stylesObj.cellXfs.length; i++) {
  472. let sheetControl = stylesObj.cellXfs[i];
  473. if (sheetControl.fontId == fontId && sheetControl.borderId == borderId) {
  474. if (private_checkControl(cellControl, sheetControl)) {
  475. rst = i;
  476. hasStyle = true;
  477. break;
  478. }
  479. }
  480. }
  481. if (!hasStyle) {
  482. let sheetControl = {};
  483. sheetControl.fontId = fontId;
  484. sheetControl.borderId = borderId;
  485. for (let i = 0; i < JV.CONTROL_PROPS.length; i++) {
  486. sheetControl[JV.CONTROL_PROPS[i]] = cellControl[JV.CONTROL_PROPS[i]];
  487. }
  488. stylesObj.cellXfs.push(sheetControl);
  489. rst = stylesObj.cellXfs.length - 1;
  490. }
  491. return rst;
  492. };
  493. private_setCols = function(){
  494. //remark: 1 excel width = 2.117 mm
  495. rst.push('<cols>');
  496. let w = 0;
  497. for (let i = 1; i < xPos.length - 1; i++) {
  498. w = 1.0 * (xPos[i + 1] - xPos[i]) / DPI * 25.4 / 2.117;
  499. w = Math.round(w * 1000) / 1000;
  500. rst.push('<col min="' + i +'" max="' + i +'" width="' + w + '" customWidth="1"/>');
  501. }
  502. rst.push('</cols>');
  503. };
  504. private_setMergedCells = function() {
  505. let cell, idxR, idxL, idxT, idxB, cnt = 0;
  506. rst.push('<mergeCells count="?">');
  507. let startIdx = rst.length - 1;
  508. self_setMergedCells = function (theData, theYPos, offsetY) {
  509. for (let i = 0; i < theData.cells.length; i++) {
  510. cell = theData.cells[i];
  511. idxR = xPos.indexOf(cell[JV.PROP_AREA][JV.PROP_RIGHT]);
  512. idxL = xPos.indexOf(cell[JV.PROP_AREA][JV.PROP_LEFT]);
  513. idxB = theYPos.indexOf(cell[JV.PROP_AREA][JV.PROP_BOTTOM]);
  514. idxT = theYPos.indexOf(cell[JV.PROP_AREA][JV.PROP_TOP]);
  515. if (idxR - idxL > 1 || idxB - idxT > 1) {
  516. rst.push('<mergeCell ref="' + private_getCellIdxStr(idxL - 1) + (idxT + offsetY) + ':' + private_getCellIdxStr(idxR - 2) + (idxB - 1 + offsetY) + '"/>');
  517. cnt++;
  518. }
  519. }
  520. }
  521. if (sheetData) {
  522. self_setMergedCells(sheetData, yPos, 0);
  523. } else {
  524. let osY = 0;
  525. for (let i = 0; i < pageData.items.length; i++) {
  526. let shtItemData = pageData.items[i];
  527. let tmpPos = yMultiPos[i];
  528. self_setMergedCells(shtItemData, tmpPos, osY);
  529. osY += tmpPos.length;
  530. }
  531. }
  532. rst[startIdx] = '<mergeCells count="' + cnt + '">';
  533. rst.push('</mergeCells>');
  534. };
  535. private_chkIfNeedCacheCell = function(cell){
  536. let rst = false;
  537. if (cell[JV.PROP_AREA][JV.PROP_LEFT] === pageData[JV.BAND_PROP_MERGE_BAND][JV.PROP_LEFT] ||
  538. cell[JV.PROP_AREA][JV.PROP_RIGHT] === pageData[JV.BAND_PROP_MERGE_BAND][JV.PROP_RIGHT] ||
  539. cell[JV.PROP_AREA][JV.PROP_TOP] === pageData[JV.BAND_PROP_MERGE_BAND][JV.PROP_TOP] ||
  540. cell[JV.PROP_AREA][JV.PROP_BOTTOM] === pageData[JV.BAND_PROP_MERGE_BAND][JV.PROP_BOTTOM]){
  541. if (cell[JV.PROP_AREA][JV.PROP_LEFT] >= pageData[JV.BAND_PROP_MERGE_BAND][JV.PROP_LEFT] &&
  542. cell[JV.PROP_AREA][JV.PROP_RIGHT] <= pageData[JV.BAND_PROP_MERGE_BAND][JV.PROP_RIGHT] &&
  543. cell[JV.PROP_AREA][JV.PROP_TOP] >= pageData[JV.BAND_PROP_MERGE_BAND][JV.PROP_TOP] &&
  544. cell[JV.PROP_AREA][JV.PROP_BOTTOM] <= pageData[JV.BAND_PROP_MERGE_BAND][JV.PROP_BOTTOM]) {
  545. rst = true;
  546. }
  547. }
  548. return rst;
  549. };
  550. private_cacheMergeBandBorderIdxs = function() {
  551. let cell, idxR, idxL, idxT, idxB;
  552. self_cachMergeIdxs = function (theData, theYPos, offsetY) {
  553. for (let i = 0; i < theData.cells.length; i++) {
  554. cell = theData.cells[i];
  555. idxR = xPos.indexOf(cell[JV.PROP_AREA][JV.PROP_RIGHT]);
  556. idxL = xPos.indexOf(cell[JV.PROP_AREA][JV.PROP_LEFT]);
  557. idxB = theYPos.indexOf(cell[JV.PROP_AREA][JV.PROP_BOTTOM]);
  558. idxT = theYPos.indexOf(cell[JV.PROP_AREA][JV.PROP_TOP]);
  559. if (idxR - idxL > 1 || idxB - idxT > 1) {
  560. if (private_chkIfNeedCacheCell(cell)) {
  561. for (let xi = idxL; xi < idxR; xi++) {
  562. for (let yj = idxT; yj < idxB; yj++) {
  563. cacheBorderCell[private_getCellIdxStr(xi - 1) + yj + offsetY] = cell;
  564. }
  565. }
  566. }
  567. }
  568. }
  569. }
  570. if (sheetData) {
  571. self_cachMergeIdxs(sheetData, yPos, 0);
  572. } else {
  573. let osY = 0;
  574. for (let i = 0; i < pageData.items.length; i++) {
  575. let shtItemData = pageData.items[i];
  576. let tmpPos = yMultiPos[i];
  577. self_cachMergeIdxs(shtItemData, tmpPos, osY);
  578. osY += tmpPos.length;
  579. }
  580. }
  581. };
  582. private_getMergedCellStyleId = function(preStyleId, colIdxStr) {
  583. let rst = preStyleId;
  584. if (cacheBorderCell[colIdxStr]) {
  585. rst = private_getStyleId(cacheBorderCell[colIdxStr]);
  586. }
  587. return rst;
  588. };
  589. private_setSheetData = function(){
  590. //remark: 1 excel height = 0.3612 mm
  591. rst.push('<sheetData>');
  592. let spanX = xPos.length - 2, cellIdx = 0, h = 0,
  593. hasMoreCols = true, nextColIdx = -1,
  594. nextRowIdx = 0
  595. ;
  596. self_setData = function (theShtData, theYPos, offsetY) {
  597. for (let i = 1; i < theYPos.length - 1; i++) {
  598. h = (theYPos[i+1] - theYPos[i]) / DPI * 25.4 / 0.3612;
  599. h = Math.round(h * 1000) / 1000;
  600. rst.push('<row r="' + (i + offsetY) + '" spans="1:' + spanX + '" ht="' + h + '" customHeight="1">');
  601. let colIdxStr = '';
  602. hasMoreCols = true;
  603. while (nextRowIdx < i) {
  604. if (cellIdx >= theShtData.cells.length || nextRowIdx > i) {
  605. break;
  606. } else {
  607. cellIdx++;
  608. nextRowIdx = theYPos.indexOf(theShtData.cells[cellIdx][JV.PROP_AREA][JV.PROP_TOP]);
  609. }
  610. }
  611. if (nextRowIdx > i) {
  612. hasMoreCols = false;
  613. }
  614. nextColIdx = xPos.indexOf(theShtData.cells[cellIdx][JV.PROP_AREA][JV.PROP_LEFT]);
  615. let preStyleIdx = 1;
  616. for (let j = 1; j < xPos.length - 1; j++) {
  617. colIdxStr = private_getCellIdxStr(j - 1);
  618. if (hasMoreCols) {
  619. if (nextColIdx == j) {
  620. let styleIdx = private_getStyleId(theShtData.cells[cellIdx]);
  621. preStyleIdx = styleIdx;
  622. if (strUtil.isEmptyString(theShtData.cells[cellIdx][JV.PROP_VALUE])) {
  623. rst.push('<c r="' + colIdxStr + (i + offsetY) + '" s="' + styleIdx + '"/>');
  624. //should setup the right style instead!
  625. } else {
  626. let valIdx = private_getSharedStrIdx(theShtData.cells[cellIdx][JV.PROP_VALUE]);
  627. rst.push('<c r="' + colIdxStr + (i + offsetY) + '" s="' + styleIdx + '" t="s">');
  628. rst.push('<v>' + valIdx + '</v>');
  629. rst.push('</c>');
  630. }
  631. cellIdx++;
  632. if (cellIdx < theShtData.cells.length) {
  633. nextRowIdx = theYPos.indexOf(theShtData.cells[cellIdx][JV.PROP_AREA][JV.PROP_TOP]);
  634. if (nextRowIdx > i) {
  635. hasMoreCols = false;
  636. } else {
  637. nextColIdx = xPos.indexOf(theShtData.cells[cellIdx][JV.PROP_AREA][JV.PROP_LEFT]);
  638. }
  639. } else {
  640. hasMoreCols = false;
  641. }
  642. } else if (nextColIdx < 0) {
  643. //impossible!
  644. console.log('has abnormal case!');
  645. hasMoreCols = false;
  646. } else {
  647. //rst.push('<c r="' + colIdxStr + (i + offsetY) + '" s="' + preStyleIdx + '"/>');
  648. rst.push('<c r="' + colIdxStr + (i + offsetY) + '" s="' + private_getMergedCellStyleId(preStyleIdx, colIdxStr + i + offsetY) + '"/>');
  649. }
  650. } else {
  651. //rst.push('<c r="' + colIdxStr + (i + offsetY) + '" s="' + preStyleIdx + '"/>');
  652. rst.push('<c r="' + colIdxStr + (i + offsetY) + '" s="' + private_getMergedCellStyleId(preStyleIdx, colIdxStr + i + offsetY) + '"/>');
  653. }
  654. }
  655. rst.push('</row>');
  656. }
  657. }
  658. private_cacheMergeBandBorderIdxs();
  659. if (sheetData) {
  660. //current sheet data
  661. nextRowIdx = yPos.indexOf(sheetData.cells[cellIdx][JV.PROP_AREA][JV.PROP_TOP]);
  662. self_setData(sheetData, yPos, 0);
  663. } else {
  664. //total data in one sheet
  665. let cnt = 0;
  666. for (let i = 0; i < pageData.items.length; i++) {
  667. let shtItemData = pageData.items[i];
  668. let tmpPos = yMultiPos[i];
  669. cellIdx = 0;
  670. nextRowIdx = tmpPos.indexOf(shtItemData.cells[cellIdx][JV.PROP_AREA][JV.PROP_TOP]);
  671. self_setData(shtItemData, tmpPos, cnt);
  672. cnt += tmpPos.length;
  673. }
  674. }
  675. rst.push('</sheetData>');
  676. };
  677. private_pre_analyze_pos();
  678. rst.push(dftHeadXml + '\r\n');
  679. rst.push('<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">');
  680. let colStr = private_getCellIdxStr(xPos.length - 3);
  681. rst.push('<dimension ref="A1:' + colStr + '' + yPos.length + '"/>');
  682. rst.push('<sheetViews><sheetView tabSelected="1" workbookViewId="0">');
  683. //rst.push('<selection sqref="A1:' + colStr + '1"/>');
  684. rst.push('<selection sqref="A1:A1"/>');
  685. rst.push('</sheetView></sheetViews>');
  686. rst.push('<sheetFormatPr defaultRowHeight="13.5"/>');
  687. private_setCols();
  688. private_setSheetData();
  689. private_setMergedCells();
  690. rst.push('<phoneticPr fontId="1" type="noConversion"/>');
  691. rst.push('<pageMargins left="0.315" right="0.215" top="0.315" bottom="0.315" header="0" footer="0"/>');
  692. let paperSizeIdx = JV.PAGES_SIZE_STR.indexOf(paperSize);
  693. let pStr = '';
  694. if (paperSizeIdx >= 0) {
  695. pStr = 'paperSize="' + JV.PAGES_SIZE_IDX[paperSizeIdx] + '"';
  696. }
  697. let orientationStr = (pageData[JV.NODE_PAGE_INFO][0] > pageData[JV.NODE_PAGE_INFO][1])?'landscape':'portrait';
  698. rst.push('<pageSetup ' + pStr + ' fitToWidth="0" fitToHeight="0" orientation="' + orientationStr + '" />');
  699. rst.push('<headerFooter alignWithMargins="0"/>');
  700. rst.push('</worksheet>');
  701. return rst;
  702. }
  703. module.exports = {
  704. exportExcel: function (pageData, paperSize, fName, options, callback) {
  705. let rptOptions = ({singlePage: false, fileName: 'report'});
  706. if (options === 'true') {
  707. rptOptions.singlePage = true;
  708. }
  709. let isSinglePage = rptOptions.singlePage;
  710. let sheets = [];
  711. if (isSinglePage) {
  712. //
  713. } else {
  714. //
  715. }
  716. for (let i = 0; i < pageData.items.length; i++) {
  717. sheets.push({sheetName: '第' + (i + 1) + '页'});
  718. }
  719. //1.
  720. let file = '[Content_Types].xml';
  721. let data = writeContentTypes(sheets, isSinglePage);
  722. let zip = new JSZip();
  723. zip.file(file, data.join(''), {compression: 'DEFLATE'});
  724. //2.
  725. let zip_rels = zip.folder('_rels');
  726. file = '.rels';
  727. data = writeRootRels();
  728. zip_rels.file(file, data.join(''), {compression: 'DEFLATE'});
  729. //3.
  730. let zip_docProps = zip.folder('docProps');
  731. file = 'app.xml';
  732. data = writeApp(sheets, isSinglePage);
  733. zip_docProps.file(file, data.join(''), {compression: 'DEFLATE'});
  734. file = 'core.xml';
  735. data = writeCore();
  736. zip_docProps.file(file, data.join(''), {compression: 'DEFLATE'});
  737. //4.
  738. let zip_xl = zip.folder('xl');
  739. file = 'workbook.xml';
  740. data = writeXlWorkBook(sheets, isSinglePage);
  741. zip_xl.file(file, data.join(''), {compression: 'DEFLATE'});
  742. let zip_rels2 = zip_xl.folder('_rels');
  743. file = 'workbook.xml.rels';
  744. data = writeXlRels(sheets, isSinglePage);
  745. zip_rels2.file(file, data.join(''), {compression: 'DEFLATE'});
  746. //5.
  747. let zip_theme = zip_xl.folder('theme');
  748. file = 'theme1.xml';
  749. data = writeTheme();
  750. zip_theme.file(file, data, {compression: 'DEFLATE'});
  751. //6.
  752. let zip_worksheets = zip_xl.folder('worksheets');
  753. let sharedStrList = [], stylesObj = {};
  754. data = writeSheets(pageData, paperSize, sharedStrList, stylesObj, isSinglePage);
  755. if (isSinglePage) {
  756. for (let i = 0; i < 1; i++) {
  757. file = 'sheet' + (i + 1) + '.xml';
  758. zip_worksheets.file(file, data[i].join(''), {compression: 'DEFLATE'});
  759. }
  760. } else {
  761. for (let i = 0; i < data.length; i++) {
  762. file = 'sheet' + (i + 1) + '.xml';
  763. zip_worksheets.file(file, data[i].join(''), {compression: 'DEFLATE'});
  764. }
  765. }
  766. file = 'sharedStrings.xml';
  767. data = writeSharedString(sharedStrList);
  768. zip_xl.file(file, data.join(''), {compression: 'DEFLATE'});
  769. file = 'styles.xml';
  770. data = writeStyles(stylesObj);
  771. zip_xl.file(file, data.join(''), {compression: 'DEFLATE'});
  772. if (fName) {
  773. let newName = '' + (new Date()).valueOf();
  774. zip.generateNodeStream({type:'nodebuffer',streamFiles:true})
  775. .pipe(fs.createWriteStream(__dirname.slice(0, __dirname.length - 21) + '/tmp/' + newName + '.xlsx'))
  776. .on('finish', function () {
  777. // JSZip generates a readable stream with a "end" event,
  778. // but is piped here in a writable stream which emits a "finish" event.
  779. console.log(newName + ".xlsx was written.");
  780. if (callback) callback(newName);
  781. }
  782. );
  783. } else {
  784. //return zip.generateNodeStream({type:'nodebuffer',streamFiles:true});
  785. return zip;
  786. }
  787. }
  788. }