rpt_excel_util.js 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853
  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. let 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. let 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. //pageData[JV.NODE_FONT_COLLECTION] excelStyle.fontId
  199. let alignStr = "<alignment";
  200. let textRotation = 0;
  201. let newHorizontal = excelStyle[JV.CONTROL_PROPS[2]];
  202. let newVertical = excelStyle[JV.CONTROL_PROPS[3]];
  203. if (parseInt(excelStyle.fontAngle) !== 0) {
  204. let tmpH = newHorizontal, tmpV = newVertical;
  205. if (excelStyle.fontAngle > 0) {
  206. textRotation = 180;
  207. if (newHorizontal === "left") {
  208. tmpV = 'top';
  209. } else if (newHorizontal === "right") {
  210. tmpV = 'bottom';
  211. } else {
  212. tmpV = 'center';
  213. }
  214. if (newVertical === "top") {
  215. tmpH = 'right';
  216. } else if (newVertical === "bottom") {
  217. tmpH = 'left';
  218. } else {
  219. tmpH = 'center';
  220. }
  221. } else {
  222. textRotation = 90;
  223. if (newHorizontal === "left") {
  224. tmpV = 'bottom';
  225. } else if (newHorizontal === "right") {
  226. tmpV = 'top';
  227. } else {
  228. tmpV = 'center';
  229. }
  230. if (newVertical === "top") {
  231. tmpH = 'left';
  232. } else if (newVertical === "bottom") {
  233. tmpH = 'right';
  234. } else {
  235. tmpH = 'center';
  236. }
  237. }
  238. newHorizontal = tmpH;
  239. newVertical = tmpV;
  240. }
  241. alignStr += ' horizontal="' + newHorizontal + '" vertical="' + newVertical + '"';
  242. if (strUtil.convertStrToBoolean(excelStyle[JV.CONTROL_PROPS[1]])) {
  243. alignStr += ' shrinkToFit="1"';
  244. }
  245. if (strUtil.convertStrToBoolean(excelStyle[JV.CONTROL_PROPS[4]])) {
  246. alignStr += ' wrapText="1"';
  247. }
  248. if (textRotation !== 0) {
  249. alignStr += ' textRotation="' + textRotation + '"';
  250. }
  251. alignStr += '/>';
  252. rst.push(alignStr);
  253. rst.push('</xf>');
  254. }
  255. rst.push('</cellXfs>');
  256. //6. others (xfl style / dxfs / tableStyles)
  257. rst.push('<cellStyles count="1"><cellStyle name="常规" xfId="0" builtinId="0"/></cellStyles>');
  258. rst.push('<dxfs count="0"/>');
  259. rst.push('<tableStyles count="0" defaultTableStyle="TableStyleMedium9" defaultPivotStyle="PivotStyleLight16"/>');
  260. rst.push('</styleSheet>');
  261. return rst;
  262. }
  263. function writeSharedString(sharedStrList){
  264. let rst = [];
  265. if (sharedStrList && sharedStrList.length > 0) {
  266. rst.push(dftHeadXml + '\r\n');
  267. rst.push('<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" count="' + sharedStrList.length + '" uniqueCount="' + sharedStrList.length + '">');
  268. for (let i = 0; i < sharedStrList.length; i++) {
  269. //rst.push('<si><t>' + sharedStrList[i] + '</t></si>');
  270. if (typeof sharedStrList[i] === 'string') {
  271. rst.push('<si><t>' + sharedStrList[i].replace('|','\r\n') + '</t></si>');
  272. } else {
  273. rst.push('<si><t>' + sharedStrList[i] + '</t></si>');
  274. }
  275. }
  276. rst.push('</sst>');
  277. }
  278. return rst;
  279. }
  280. function writeSheets(pageData, paperSize, sharedStrList, stylesObj, isSinglePage){
  281. let rst = [];
  282. let private_pushDftFont = function(){
  283. let font = {};
  284. if (!(stylesObj.fonts)) {
  285. stylesObj.fonts = [];
  286. }
  287. font[JV.FONT_PROPS[0]] = "宋体"; //font name
  288. font.size = 12;
  289. font.charset = 134;
  290. font.colorIdx = "8";
  291. stylesObj.fonts.push(font);
  292. };
  293. let private_buildFirstDftStyle = function () {
  294. stylesObj.cellXfs = [];
  295. stylesObj.borders = [];
  296. let fontId = 0;
  297. let borderId = 0;
  298. let border = {};
  299. border[JV.PROP_LEFT] = {};
  300. border[JV.PROP_LEFT][JV.PROP_LINE_WEIGHT] = 0;
  301. border[JV.PROP_RIGHT] = {};
  302. border[JV.PROP_RIGHT][JV.PROP_LINE_WEIGHT] = 0;
  303. border[JV.PROP_TOP] = {};
  304. border[JV.PROP_TOP][JV.PROP_LINE_WEIGHT] = 0;
  305. border[JV.PROP_BOTTOM] = {};
  306. border[JV.PROP_BOTTOM][JV.PROP_LINE_WEIGHT] = 0;
  307. stylesObj.borders.push(border);
  308. let cellControl = pageData[JV.NODE_CONTROL_COLLECTION].Default;
  309. let sheetControl = {};
  310. sheetControl.fontId = fontId;
  311. sheetControl.borderId = borderId;
  312. sheetControl.fontAngle = 0;
  313. for (let i = 0; i < JV.CONTROL_PROPS.length; i++) {
  314. sheetControl[JV.CONTROL_PROPS[i]] = cellControl[JV.CONTROL_PROPS[i]];
  315. }
  316. stylesObj.cellXfs.push(sheetControl);
  317. }
  318. private_pushDftFont();
  319. private_buildFirstDftStyle();
  320. if (isSinglePage) {
  321. rst.push(writeSheet(pageData, null, paperSize, sharedStrList, stylesObj));
  322. } else {
  323. for (let i = 0; i < pageData.items.length; i++) {
  324. rst.push(writeSheet(pageData, pageData.items[i], paperSize, sharedStrList, stylesObj));
  325. }
  326. }
  327. return rst;
  328. }
  329. function writeSheet(pageData, sheetData, paperSize, sharedStrList, stylesObj){
  330. let rst = [], xPos = [], yPos = [], yMultiPos = [], headerStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  331. let cacheBorderCell = {};
  332. let private_pre_analyze_pos = function(){
  333. let cell, pos;
  334. let self_analyze_sheet_pos = function (theShtData, theXPos, theYPos) {
  335. theShtData.cells.sort(function(cell1, cell2) {
  336. let rst = 0;
  337. if (cell1[JV.PROP_AREA][JV.PROP_TOP] > cell2[JV.PROP_AREA][JV.PROP_TOP]) {
  338. rst = 1;
  339. } else if (cell1[JV.PROP_AREA][JV.PROP_TOP] < cell2[JV.PROP_AREA][JV.PROP_TOP]) {
  340. rst = -1;
  341. } else {
  342. if (cell1[JV.PROP_AREA][JV.PROP_LEFT] > cell2[JV.PROP_AREA][JV.PROP_LEFT]) {
  343. rst = 1;
  344. } else if (cell1[JV.PROP_AREA][JV.PROP_LEFT] < cell2[JV.PROP_AREA][JV.PROP_LEFT]) {
  345. rst = -1;
  346. }
  347. }
  348. return rst;
  349. });
  350. for (let i = 0; i < theShtData.cells.length; i++) {
  351. cell = theShtData.cells[i];
  352. pos = cell[JV.PROP_AREA][JV.PROP_LEFT];
  353. if (theXPos.indexOf(pos) < 0) theXPos.push(pos);
  354. pos = cell[JV.PROP_AREA][JV.PROP_RIGHT];
  355. if (theXPos.indexOf(pos) < 0) theXPos.push(pos);
  356. pos = cell[JV.PROP_AREA][JV.PROP_TOP];
  357. if (theYPos.indexOf(pos) < 0) theYPos.push(pos);
  358. pos = cell[JV.PROP_AREA][JV.PROP_BOTTOM];
  359. if (theYPos.indexOf(pos) < 0) theYPos.push(pos);
  360. }
  361. };
  362. xPos.push(0);
  363. if (sheetData) {
  364. //current sheet data
  365. yPos.push(0);
  366. self_analyze_sheet_pos(sheetData, xPos, yPos);
  367. xPos.sort(private_array_sort);
  368. yPos.sort(private_array_sort);
  369. } else {
  370. //total data in one sheet
  371. for (let shtItemData of pageData.items) {
  372. let tmpPos = [];
  373. tmpPos.push(0);
  374. self_analyze_sheet_pos(shtItemData, xPos, tmpPos);
  375. tmpPos.sort(private_array_sort);
  376. yMultiPos.push(tmpPos);
  377. }
  378. xPos.sort(private_array_sort);
  379. yPos = yMultiPos[0];
  380. }
  381. };
  382. let private_array_sort = function(i1, i2){
  383. let rst = 0;
  384. if (i1 > i2) {rst = 1} else
  385. if (i1 < i2) rst = -1;
  386. return rst;
  387. };
  388. let private_getCellIdxStr = function(idx){
  389. let rst = 'A';
  390. if (idx < 26) {
  391. rst = headerStr[idx];
  392. } else if (idx < 26*26+26) {
  393. let ti = Math.floor(idx / 26), tj = idx % 26;
  394. rst = headerStr[ti - 1] + headerStr[tj];
  395. } else if (idx < 26*26*26+26) {
  396. let ti = Math.floor(idx / (26*26)), tj = Math.floor((idx - ti * 26*26) / 26), tk = idx % 26;
  397. rst = headerStr[ti - 1] + headerStr[tj-1] + headerStr[tk];
  398. }
  399. return rst;
  400. };
  401. let private_getSharedStrIdx = function(val) {
  402. let rst = sharedStrList.indexOf(val);
  403. if (rst < 0) {
  404. sharedStrList.push(val);
  405. rst = sharedStrList.length - 1;
  406. }
  407. return rst;
  408. };
  409. let private_getFontId = function(cell) {
  410. let rst = 0, hasFont = false;
  411. if (!(stylesObj.fonts)) {
  412. stylesObj.fonts = [];
  413. //for (let i = 0; i < sheetData.font_collection)
  414. }
  415. let sheetFont = pageData.font_collection[cell.font];
  416. for (let i = 0; i < stylesObj.fonts.length; i++) {
  417. let font = stylesObj.fonts[i];
  418. if (sheetFont) {
  419. 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]]) {
  420. hasFont = true;
  421. rst = i;
  422. break;
  423. }
  424. } else {
  425. break;
  426. }
  427. }
  428. if (!hasFont) {
  429. let font = {};
  430. font[JV.FONT_PROPS[0]] = sheetFont[JV.FONT_PROPS[0]]; //font name
  431. font.size = Math.round(sheetFont[JV.FONT_PROPS[1]] * 3 / 4);
  432. font.charset = 134;
  433. font.colorIdx = "8";
  434. font[JV.FONT_PROPS[3]] = sheetFont[JV.FONT_PROPS[3]]; //font bold
  435. stylesObj.fonts.push(font);
  436. rst = stylesObj.fonts.length - 1;
  437. }
  438. return rst;
  439. };
  440. let private_checkBorder = function(cell, border, sheetBorder) {
  441. let rst = true, borderLineWidths = [], sheetBorderLineWidths = [];
  442. borderLineWidths.push(border[JV.PROP_LEFT][JV.PROP_LINE_WEIGHT]);
  443. borderLineWidths.push(border[JV.PROP_RIGHT][JV.PROP_LINE_WEIGHT]);
  444. borderLineWidths.push(border[JV.PROP_TOP][JV.PROP_LINE_WEIGHT]);
  445. borderLineWidths.push(border[JV.PROP_BOTTOM][JV.PROP_LINE_WEIGHT]);
  446. if (sheetBorder[JV.PROP_LEFT] && sheetBorder[JV.PROP_LEFT][JV.PROP_LINE_WEIGHT]) {
  447. sheetBorderLineWidths.push(private_chkAndGetMergeLine(cell, sheetBorder, JV.PROP_LEFT));
  448. } else {
  449. sheetBorderLineWidths.push(0);
  450. }
  451. if (sheetBorder[JV.PROP_RIGHT] && sheetBorder[JV.PROP_RIGHT][JV.PROP_LINE_WEIGHT]) {
  452. sheetBorderLineWidths.push(private_chkAndGetMergeLine(cell, sheetBorder, JV.PROP_RIGHT));
  453. } else {
  454. sheetBorderLineWidths.push(0);
  455. }
  456. if (sheetBorder[JV.PROP_TOP] && sheetBorder[JV.PROP_TOP][JV.PROP_LINE_WEIGHT]) {
  457. sheetBorderLineWidths.push(private_chkAndGetMergeLine(cell, sheetBorder, JV.PROP_TOP));
  458. } else {
  459. sheetBorderLineWidths.push(0);
  460. }
  461. if (sheetBorder[JV.PROP_BOTTOM] && sheetBorder[JV.PROP_BOTTOM][JV.PROP_LINE_WEIGHT]) {
  462. sheetBorderLineWidths.push(private_chkAndGetMergeLine(cell, sheetBorder, JV.PROP_BOTTOM));
  463. } else {
  464. sheetBorderLineWidths.push(0);
  465. }
  466. for (let i = 0; i < 4; i++) {
  467. if (borderLineWidths[i] != sheetBorderLineWidths[i]) {
  468. rst = false;
  469. break;
  470. }
  471. }
  472. return rst;
  473. };
  474. let private_chkAndGetMergeLine = function(cell, sheetBorder, borderStr) {
  475. let rst = 0, mergeBorder = pageData[JV.BAND_PROP_MERGE_BAND];
  476. if (sheetBorder[borderStr] && sheetBorder[borderStr][JV.PROP_LINE_WEIGHT] != undefined) {
  477. rst = sheetBorder[borderStr][JV.PROP_LINE_WEIGHT];
  478. }
  479. if (cell[JV.PROP_AREA][borderStr] == mergeBorder[borderStr]) {
  480. let destStyle = pageData[JV.NODE_STYLE_COLLECTION][mergeBorder[JV.PROP_STYLE][JV.PROP_ID]];
  481. rst = destStyle[borderStr][JV.PROP_LINE_WEIGHT];
  482. }
  483. return parseInt(rst);
  484. };
  485. let private_getIniBorder = function() {
  486. let rst = {};
  487. rst[JV.PROP_LEFT] = {};
  488. rst[JV.PROP_LEFT][JV.PROP_LINE_WEIGHT] = 0;
  489. rst[JV.PROP_RIGHT] = {};
  490. rst[JV.PROP_RIGHT][JV.PROP_LINE_WEIGHT] = 0;
  491. rst[JV.PROP_TOP] = {};
  492. rst[JV.PROP_TOP][JV.PROP_LINE_WEIGHT] = 0;
  493. rst[JV.PROP_BOTTOM] = {};
  494. rst[JV.PROP_BOTTOM][JV.PROP_LINE_WEIGHT] = 0;
  495. return rst;
  496. };
  497. let private_getBorderId = function(cell) {
  498. let rst = 0, hasBorder = false;
  499. if (!(stylesObj.borders)) {
  500. stylesObj.borders = [];
  501. }
  502. let sheetBorder = pageData[JV.NODE_STYLE_COLLECTION][cell.style];
  503. let mergedBorder = private_getIniBorder();
  504. mergedBorder[JV.PROP_LEFT][JV.PROP_LINE_WEIGHT] = private_chkAndGetMergeLine(cell, sheetBorder, JV.PROP_LEFT);
  505. mergedBorder[JV.PROP_RIGHT][JV.PROP_LINE_WEIGHT] = private_chkAndGetMergeLine(cell, sheetBorder, JV.PROP_RIGHT);
  506. mergedBorder[JV.PROP_TOP][JV.PROP_LINE_WEIGHT] = private_chkAndGetMergeLine(cell, sheetBorder, JV.PROP_TOP);
  507. mergedBorder[JV.PROP_BOTTOM][JV.PROP_LINE_WEIGHT] = private_chkAndGetMergeLine(cell, sheetBorder, JV.PROP_BOTTOM);
  508. for (let i = 0; i < stylesObj.borders.length; i++) {
  509. let border = stylesObj.borders[i];
  510. if (private_checkBorder(cell, border, mergedBorder)) {
  511. hasBorder = true;
  512. rst = i;
  513. break;
  514. }
  515. }
  516. if (!hasBorder) {
  517. stylesObj.borders.push(mergedBorder);
  518. rst = stylesObj.borders.length - 1;
  519. }
  520. return rst;
  521. };
  522. let private_checkControl = function(cellControl, sheetControl) {
  523. let rst = true;
  524. for (let i = 0; i < JV.CONTROL_PROPS.length; i++) {
  525. if (cellControl[JV.CONTROL_PROPS[i]] != sheetControl[JV.CONTROL_PROPS[i]]) {
  526. rst = false;
  527. break;
  528. }
  529. }
  530. return rst;
  531. };
  532. let private_getStyleId = function(cell) {
  533. let rst = 1, hasStyle = false;
  534. if (!(stylesObj.cellXfs)) stylesObj.cellXfs = [];
  535. let fontId = private_getFontId(cell);
  536. let fontAngle = parseInt(pageData.font_collection[cell.font].FontAngle);
  537. let borderId = private_getBorderId(cell);
  538. let cellControl = pageData[JV.NODE_CONTROL_COLLECTION][cell[JV.PROP_CONTROL]];
  539. for (let i = 0; i < stylesObj.cellXfs.length; i++) {
  540. let sheetControl = stylesObj.cellXfs[i];
  541. if (sheetControl.fontId == fontId && sheetControl.borderId == borderId) {
  542. if (private_checkControl(cellControl, sheetControl)) {
  543. rst = i;
  544. hasStyle = true;
  545. break;
  546. }
  547. }
  548. }
  549. if (!hasStyle) {
  550. let sheetControl = {};
  551. sheetControl.fontId = fontId;
  552. sheetControl.borderId = borderId;
  553. sheetControl.fontAngle = fontAngle;
  554. for (let i = 0; i < JV.CONTROL_PROPS.length; i++) {
  555. sheetControl[JV.CONTROL_PROPS[i]] = cellControl[JV.CONTROL_PROPS[i]];
  556. }
  557. stylesObj.cellXfs.push(sheetControl);
  558. rst = stylesObj.cellXfs.length - 1;
  559. }
  560. return rst;
  561. };
  562. let private_setCols = function(){
  563. //remark: 1 excel width = 2.117 mm
  564. rst.push('<cols>');
  565. let w = 0;
  566. for (let i = 1; i < xPos.length - 1; i++) {
  567. w = 1.0 * (xPos[i + 1] - xPos[i]) / DPI * 25.4 / 2.117;
  568. w = Math.round(w * 1000) / 1000;
  569. rst.push('<col min="' + i +'" max="' + i +'" width="' + w + '" customWidth="1"/>');
  570. }
  571. rst.push('</cols>');
  572. };
  573. let private_setMergedCells = function() {
  574. let cell, idxR, idxL, idxT, idxB, cnt = 0;
  575. rst.push('<mergeCells count="?">');
  576. let startIdx = rst.length - 1;
  577. let self_setMergedCells = function (theData, theYPos, offsetY) {
  578. for (let i = 0; i < theData.cells.length; i++) {
  579. cell = theData.cells[i];
  580. idxR = xPos.indexOf(cell[JV.PROP_AREA][JV.PROP_RIGHT]);
  581. idxL = xPos.indexOf(cell[JV.PROP_AREA][JV.PROP_LEFT]);
  582. idxB = theYPos.indexOf(cell[JV.PROP_AREA][JV.PROP_BOTTOM]);
  583. idxT = theYPos.indexOf(cell[JV.PROP_AREA][JV.PROP_TOP]);
  584. if (idxR - idxL > 1 || idxB - idxT > 1) {
  585. rst.push('<mergeCell ref="' + private_getCellIdxStr(idxL - 1) + (idxT + offsetY) + ':' + private_getCellIdxStr(idxR - 2) + (idxB - 1 + offsetY) + '"/>');
  586. cnt++;
  587. }
  588. }
  589. }
  590. if (sheetData) {
  591. self_setMergedCells(sheetData, yPos, 0);
  592. } else {
  593. let osY = 0;
  594. for (let i = 0; i < pageData.items.length; i++) {
  595. let shtItemData = pageData.items[i];
  596. let tmpPos = yMultiPos[i];
  597. self_setMergedCells(shtItemData, tmpPos, osY);
  598. osY += tmpPos.length - 2;
  599. }
  600. }
  601. rst[startIdx] = '<mergeCells count="' + cnt + '">';
  602. rst.push('</mergeCells>');
  603. };
  604. let private_chkIfNeedCacheCell = function(cell){
  605. let rst = false;
  606. if (cell[JV.PROP_AREA][JV.PROP_LEFT] === pageData[JV.BAND_PROP_MERGE_BAND][JV.PROP_LEFT] ||
  607. cell[JV.PROP_AREA][JV.PROP_RIGHT] === pageData[JV.BAND_PROP_MERGE_BAND][JV.PROP_RIGHT] ||
  608. cell[JV.PROP_AREA][JV.PROP_TOP] === pageData[JV.BAND_PROP_MERGE_BAND][JV.PROP_TOP] ||
  609. cell[JV.PROP_AREA][JV.PROP_BOTTOM] === pageData[JV.BAND_PROP_MERGE_BAND][JV.PROP_BOTTOM]){
  610. if (cell[JV.PROP_AREA][JV.PROP_LEFT] >= pageData[JV.BAND_PROP_MERGE_BAND][JV.PROP_LEFT] &&
  611. cell[JV.PROP_AREA][JV.PROP_RIGHT] <= pageData[JV.BAND_PROP_MERGE_BAND][JV.PROP_RIGHT] &&
  612. cell[JV.PROP_AREA][JV.PROP_TOP] >= pageData[JV.BAND_PROP_MERGE_BAND][JV.PROP_TOP] &&
  613. cell[JV.PROP_AREA][JV.PROP_BOTTOM] <= pageData[JV.BAND_PROP_MERGE_BAND][JV.PROP_BOTTOM]) {
  614. rst = true;
  615. }
  616. }
  617. return rst;
  618. };
  619. let private_cacheMergeBandBorderIdxs = function() {
  620. let cell, idxR, idxL, idxT, idxB;
  621. let self_cachMergeIdxs = function (theData, theYPos, offsetY) {
  622. for (let i = 0; i < theData.cells.length; i++) {
  623. cell = theData.cells[i];
  624. idxR = xPos.indexOf(cell[JV.PROP_AREA][JV.PROP_RIGHT]);
  625. idxL = xPos.indexOf(cell[JV.PROP_AREA][JV.PROP_LEFT]);
  626. idxB = theYPos.indexOf(cell[JV.PROP_AREA][JV.PROP_BOTTOM]);
  627. idxT = theYPos.indexOf(cell[JV.PROP_AREA][JV.PROP_TOP]);
  628. if (idxR - idxL > 1 || idxB - idxT > 1) {
  629. if (private_chkIfNeedCacheCell(cell)) {
  630. for (let xi = idxL; xi < idxR; xi++) {
  631. for (let yj = idxT; yj < idxB; yj++) {
  632. cacheBorderCell[private_getCellIdxStr(xi - 1) + yj + offsetY] = cell;
  633. }
  634. }
  635. }
  636. }
  637. }
  638. }
  639. if (sheetData) {
  640. self_cachMergeIdxs(sheetData, yPos, 0);
  641. } else {
  642. let osY = 0;
  643. for (let i = 0; i < pageData.items.length; i++) {
  644. let shtItemData = pageData.items[i];
  645. let tmpPos = yMultiPos[i];
  646. self_cachMergeIdxs(shtItemData, tmpPos, osY);
  647. osY += tmpPos.length - 2;
  648. }
  649. }
  650. };
  651. let private_setSheetData = function(){
  652. //remark: 1 excel height = 0.3612 mm
  653. rst.push('<sheetData>');
  654. let spanX = xPos.length - 2, cellIdx = 0, h = 0
  655. ;
  656. let self_setDataEx = function (theShtData, theYPos, offsetY) {
  657. let rows = [];
  658. //1. build full set of blank rows/cells
  659. for (let i = 1; i < theYPos.length - 1; i++) {
  660. let rowObj = {};
  661. h = (theYPos[i+1] - theYPos[i]) / DPI * 25.4 / 0.3612;
  662. h = Math.round(h * 1000) / 1000;
  663. rowObj.height = h;
  664. rowObj.r = i + offsetY;
  665. rowObj.items = [];
  666. rows.push(rowObj);
  667. for (let j = 1; j < xPos.length - 1; j++) {
  668. let colIdxStr = private_getCellIdxStr(j - 1);
  669. let cellObj = {};
  670. cellObj.r = colIdxStr + (i + offsetY);
  671. cellObj.s = 0;
  672. cellObj.isBlank = true;
  673. rows[i - 1].items.push(cellObj);
  674. }
  675. }
  676. //2. then fill up the cell style-ids and values
  677. let rowIdx1 = 0, colIdx1 = 0, rowIdx2 = 0, colIdx2 = 0, colIdxStr = '';
  678. for (let cIdx = 0; cIdx < theShtData.cells.length; cIdx++) {
  679. let styleIdx = private_getStyleId(theShtData.cells[cIdx]);
  680. //colIdxStr = private_getCellIdxStr(j - 1);
  681. rowIdx1 = theYPos.indexOf(theShtData.cells[cIdx][JV.PROP_AREA][JV.PROP_TOP]);
  682. colIdx1 = xPos.indexOf(theShtData.cells[cIdx][JV.PROP_AREA][JV.PROP_LEFT]);
  683. let cellObj = rows[rowIdx1 - 1].items[colIdx1 - 1];
  684. cellObj.s = styleIdx;
  685. cellObj.isBlank = false;
  686. if (!(strUtil.isEmptyString(theShtData.cells[cIdx][JV.PROP_VALUE]))) {
  687. let valIdx = private_getSharedStrIdx(theShtData.cells[cIdx][JV.PROP_VALUE]);
  688. cellObj.v = valIdx;
  689. }
  690. rowIdx2 = theYPos.indexOf(theShtData.cells[cIdx][JV.PROP_AREA][JV.PROP_BOTTOM]);
  691. colIdx2 = xPos.indexOf(theShtData.cells[cIdx][JV.PROP_AREA][JV.PROP_RIGHT]);
  692. if ((rowIdx2 - rowIdx1 > 1) || (colIdx2 - colIdx1 > 1)) {
  693. for (let i = 0; i < rowIdx2 - rowIdx1; i++) {
  694. for (let j = 0; j < colIdx2 - colIdx1; j++) {
  695. if (i === 0 && j === 0) continue;
  696. cellObj = rows[rowIdx1 - 1 + i].items[colIdx1 - 1 + j];
  697. cellObj.s = styleIdx;
  698. cellObj.isBlank = true;
  699. }
  700. }
  701. }
  702. }
  703. //3. then fill up rst
  704. for (let i = 0; i < rows.length; i++) {
  705. rst.push('<row r="' + (i + 1 + offsetY) + '" spans="1:' + spanX + '" ht="' + rows[i].height + '" customHeight="1">');
  706. for (let j = 0; j < rows[i].items.length; j++) {
  707. let cellObj = rows[i].items[j];
  708. if (cellObj.v === undefined) {
  709. rst.push('<c r="' + cellObj.r + '" s="' + cellObj.s + '"/>');
  710. } else {
  711. rst.push('<c r="' + cellObj.r + '" s="' + cellObj.s + '" t="s">');
  712. rst.push('<v>' + cellObj.v + '</v>');
  713. rst.push('</c>');
  714. }
  715. }
  716. rst.push('</row>');
  717. }
  718. //4. maybe need to dispose the memory
  719. //...
  720. };
  721. private_cacheMergeBandBorderIdxs();
  722. if (sheetData) {
  723. //current sheet data
  724. self_setDataEx(sheetData, yPos, 0);
  725. } else {
  726. //total data in one sheet
  727. let cnt = 0;
  728. for (let i = 0; i < pageData.items.length; i++) {
  729. let shtItemData = pageData.items[i];
  730. let tmpPos = yMultiPos[i];
  731. cellIdx = 0;
  732. self_setDataEx(shtItemData, tmpPos, cnt);
  733. cnt += tmpPos.length - 2;
  734. }
  735. }
  736. rst.push('</sheetData>');
  737. };
  738. private_pre_analyze_pos();
  739. rst.push(dftHeadXml + '\r\n');
  740. rst.push('<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">');
  741. let colStr = private_getCellIdxStr(xPos.length - 3);
  742. rst.push('<dimension ref="A1:' + colStr + '' + yPos.length + '"/>');
  743. rst.push('<sheetViews><sheetView tabSelected="1" workbookViewId="0">');
  744. //rst.push('<selection sqref="A1:' + colStr + '1"/>');
  745. rst.push('<selection sqref="A1:A1"/>');
  746. rst.push('</sheetView></sheetViews>');
  747. rst.push('<sheetFormatPr defaultRowHeight="13.5"/>');
  748. private_setCols();
  749. private_setSheetData();
  750. private_setMergedCells();
  751. rst.push('<phoneticPr fontId="1" type="noConversion"/>');
  752. rst.push('<pageMargins left="0.315" right="0.215" top="0.315" bottom="0.315" header="0" footer="0"/>');
  753. let paperSizeIdx = JV.PAGES_SIZE_STR.indexOf(paperSize);
  754. let pStr = '';
  755. if (paperSizeIdx >= 0) {
  756. pStr = 'paperSize="' + JV.PAGES_SIZE_IDX[paperSizeIdx] + '"';
  757. }
  758. let orientationStr = (pageData[JV.NODE_PAGE_INFO][0] > pageData[JV.NODE_PAGE_INFO][1])?'landscape':'portrait';
  759. rst.push('<pageSetup ' + pStr + ' fitToWidth="0" fitToHeight="0" orientation="' + orientationStr + '" />');
  760. rst.push('<headerFooter alignWithMargins="0"/>');
  761. rst.push('</worksheet>');
  762. return rst;
  763. }
  764. module.exports = {
  765. exportExcel: function (pageData, paperSize, fName, options, callback) {
  766. let rptOptions = ({singlePage: false, fileName: 'report'});
  767. if (options === 'true') {
  768. rptOptions.singlePage = true;
  769. }
  770. let isSinglePage = rptOptions.singlePage;
  771. let sheets = [];
  772. if (isSinglePage) {
  773. sheets.push({sheetName: '全部页'});
  774. } else {
  775. for (let i = 0; i < pageData.items.length; i++) {
  776. sheets.push({sheetName: '第' + (i + 1) + '页'});
  777. }
  778. }
  779. //1.
  780. let file = '[Content_Types].xml';
  781. let data = writeContentTypes(sheets, isSinglePage);
  782. let zip = new JSZip();
  783. zip.file(file, data.join(''), {compression: 'DEFLATE'});
  784. //2.
  785. let zip_rels = zip.folder('_rels');
  786. file = '.rels';
  787. data = writeRootRels();
  788. zip_rels.file(file, data.join(''), {compression: 'DEFLATE'});
  789. //3.
  790. let zip_docProps = zip.folder('docProps');
  791. file = 'app.xml';
  792. data = writeApp(sheets, isSinglePage);
  793. zip_docProps.file(file, data.join(''), {compression: 'DEFLATE'});
  794. file = 'core.xml';
  795. data = writeCore();
  796. zip_docProps.file(file, data.join(''), {compression: 'DEFLATE'});
  797. //4.
  798. let zip_xl = zip.folder('xl');
  799. file = 'workbook.xml';
  800. data = writeXlWorkBook(sheets, isSinglePage);
  801. zip_xl.file(file, data.join(''), {compression: 'DEFLATE'});
  802. let zip_rels2 = zip_xl.folder('_rels');
  803. file = 'workbook.xml.rels';
  804. data = writeXlRels(sheets, isSinglePage);
  805. zip_rels2.file(file, data.join(''), {compression: 'DEFLATE'});
  806. //5.
  807. let zip_theme = zip_xl.folder('theme');
  808. file = 'theme1.xml';
  809. data = writeTheme();
  810. zip_theme.file(file, data, {compression: 'DEFLATE'});
  811. //6.
  812. let zip_worksheets = zip_xl.folder('worksheets');
  813. let sharedStrList = [], stylesObj = {};
  814. data = writeSheets(pageData, paperSize, sharedStrList, stylesObj, isSinglePage);
  815. if (isSinglePage) {
  816. for (let i = 0; i < 1; i++) {
  817. file = 'sheet' + (i + 1) + '.xml';
  818. zip_worksheets.file(file, data[i].join(''), {compression: 'DEFLATE'});
  819. }
  820. } else {
  821. for (let i = 0; i < data.length; i++) {
  822. file = 'sheet' + (i + 1) + '.xml';
  823. zip_worksheets.file(file, data[i].join(''), {compression: 'DEFLATE'});
  824. }
  825. }
  826. file = 'sharedStrings.xml';
  827. data = writeSharedString(sharedStrList);
  828. zip_xl.file(file, data.join(''), {compression: 'DEFLATE'});
  829. file = 'styles.xml';
  830. data = writeStyles(stylesObj);
  831. zip_xl.file(file, data.join(''), {compression: 'DEFLATE'});
  832. if (fName) {
  833. let newName = '' + (new Date()).valueOf();
  834. zip.generateNodeStream({type:'nodebuffer',streamFiles:true})
  835. .pipe(fs.createWriteStream(__dirname.slice(0, __dirname.length - 21) + '/tmp/' + newName + '.xlsx'))
  836. .on('finish', function () {
  837. // JSZip generates a readable stream with a "end" event,
  838. // but is piped here in a writable stream which emits a "finish" event.
  839. console.log(newName + ".xlsx was written.");
  840. if (callback) callback(newName);
  841. }
  842. );
  843. } else {
  844. //return zip.generateNodeStream({type:'nodebuffer',streamFiles:true});
  845. return zip;
  846. }
  847. }
  848. }