spreadjs_zh.js 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414
  1. /**
  2. * Spreadjs 通用方法集
  3. *
  4. * @author Mai
  5. * @date 2018/02/06
  6. * @version
  7. */
  8. // 定义画点线的方法
  9. const proto = window.CanvasRenderingContext2D && CanvasRenderingContext2D.prototype;
  10. proto.dottedLine = function (x1, y1, x2, y2, interval = 4) {
  11. const isHorizontal = x1 == x2 ? false : true;
  12. const dotLen = 1;
  13. let len = isHorizontal ? x2 - x1 : y2 - y1;
  14. this.moveTo(x1, y1);
  15. let progress = 0;
  16. while (len > progress) {
  17. if (progress > len) { progress = len; }
  18. if (isHorizontal) {
  19. this.moveTo(x1 + progress, y1);
  20. this.lineTo(x1 + progress + dotLen, y1);
  21. } else {
  22. this.moveTo(x1, y1 + progress);
  23. this.lineTo(x1, y1 + progress + dotLen);
  24. }
  25. progress += interval;
  26. }
  27. };
  28. // 简写Spread常量
  29. const spreadNS = GC.Spread.Sheets;
  30. // SpreadJs常用方法
  31. const SpreadJsObj = {
  32. initSpreadSettingEvents: function (setting, events) {
  33. const getEvent = function (eventName) {
  34. const names = eventName.split('.');
  35. let event = events;
  36. for (let name of names) {
  37. if (event[name]) {
  38. event = event[name];
  39. } else {
  40. return null;
  41. }
  42. }
  43. if (event && Object.prototype.toString.apply(event) !== "[object Function]") {
  44. return null;
  45. } else {
  46. return event;
  47. }
  48. };
  49. for (const col of setting.cols) {
  50. if (col.readOnly && Object.prototype.toString.apply(col.readOnly) === "[object String]") {
  51. col.readOnly = getEvent(col.readOnly);
  52. }
  53. if (col.getValue && Object.prototype.toString.apply(col.getValue) === "[object String]") {
  54. col.getValue = getEvent(col.getValue);
  55. }
  56. }
  57. },
  58. DataType: {
  59. Data: 'data',
  60. Tree: 'tree',
  61. },
  62. /**
  63. * 创建Spread(默认1张表,3行数据)
  64. * @param obj 用于创建spreadjs的Dom元素
  65. * @returns {GC.Spread.Sheets.Workbook}
  66. */
  67. createNewSpread: function (obj) {
  68. const spread = new spreadNS.Workbook(obj, {sheetCount: 1});
  69. spread.options.tabStripVisible = false;
  70. spread.options.scrollbarMaxAlign = true;
  71. spread.options.cutCopyIndicatorVisible = false;
  72. spread.options.allowCopyPasteExcelStyle = false;
  73. spread.options.allowUserDragDrop = false;
  74. spread.options.allowUserEditFormula = false;
  75. spread.getActiveSheet().options.clipBoardOptions = GC.Spread.Sheets.ClipboardPasteOptions.values;//设置粘贴时只粘贴值
  76. spread.getActiveSheet().setRowCount(3);
  77. return spread;
  78. },
  79. /**
  80. * 保护sheet(需设置保护后, 单元格的locked等属性方可生效)
  81. * @param {GC.Spread.Sheets.Worksheet} sheet
  82. */
  83. protectedSheet: function (sheet) {
  84. const option = {
  85. allowSelectLockedCells: true,
  86. allowSelectUnlockedCells: true,
  87. allowResizeRows: true,
  88. allowResizeColumns: true
  89. };
  90. sheet.options.protectionOptions = option;
  91. sheet.options.isProtected = true;
  92. sheet.options.allowCellOverflow = false;
  93. },
  94. /**
  95. * sheet批量操作优化(sheet操作大批量数据时, 屏蔽数据刷新, 可优化大量时间)
  96. * @param {GC.Spread.Sheets.Worksheet} sheet
  97. * @param {function} operation
  98. */
  99. beginMassOperation: function (sheet) {
  100. sheet.suspendPaint();
  101. sheet.suspendEvent();
  102. },
  103. endMassOperation: function (sheet) {
  104. sheet.resumeEvent();
  105. sheet.resumePaint();
  106. },
  107. massOperationSheet: function (sheet, operation) {
  108. this.beginMassOperation(sheet);
  109. operation();
  110. this.endMassOperation(sheet);
  111. },
  112. /**
  113. * 获取Obj左顶点位置(部分功能需通过spreadjs左顶点位置计算)
  114. * @param obj
  115. * @returns {{x: number, y: number}}
  116. */
  117. getObjPos: function (obj) {
  118. let target = obj;
  119. let pos = {x: obj.offsetLeft, y: obj.offsetTop};
  120. target = obj.offsetParent;
  121. while (target) {
  122. pos.x += target.offsetLeft;
  123. pos.y += target.offsetTop;
  124. target = target.offsetParent;
  125. }
  126. return pos;
  127. },
  128. /**
  129. * 以下四个方法来自Spread示例, 参见官网或文档
  130. */
  131. getHitTest: function (obj, e, sheet) {
  132. var offset = obj.offset(),
  133. x = e.pageX - offset.left,
  134. y = e.pageY - offset.top;
  135. return sheet.hitTest(x, y);
  136. },
  137. getTargetSelection: function (sheet, target) {
  138. if (target.hitTestType === spreadNS.SheetArea.colHeader) {
  139. return sheet.getRange(-1, target.col, sheet.getRowCount(), 1);
  140. } else if (target.hitTestType === spreadNS.SheetArea.rowHeader) {
  141. return sheet.getRange(target.row, -1, 1, sheet.getColumnCount());
  142. } else if (target.hitTestType === spreadNS.SheetArea.viewport) {
  143. return sheet.getRange(target.row, target.col, 1, 1);
  144. } else if (target.hitTestType === spreadNS.SheetArea.corner) {
  145. return sheet.getRange(-1, -1, sheet.getRowCount(), sheet.getColumnCount());
  146. };
  147. },
  148. getCellInSelections: function (selections, row, col) {
  149. const count = selections.length;
  150. let range;
  151. for (var i = 0; i < count; i++) {
  152. range = selections[i];
  153. if (range.contains(row, col)) {
  154. return range;
  155. }
  156. }
  157. return null;
  158. },
  159. checkTargetInSelection: function (selections, range) {
  160. var count = selections.length, sel;
  161. for (var i = 0; i < count; i++) {
  162. sel = selections[i];
  163. if (sel.containsRange(range)) {
  164. return true;
  165. }
  166. }
  167. return false;
  168. },
  169. /**
  170. * 获取 spread 在鼠标右键时, spread的选中区域
  171. * viewport, 选中鼠标点击单元格X, X不在原选中区域内, 则选中X
  172. * colHeader, 选中整列
  173. * rowHeader, 选中整行
  174. * corner, 全选
  175. * 该方法返回不符合需求时,可通过getHitTest/getTargetSelection/getCellInSelections/checkTargetInSelection来确定鼠标右键点击时,spread当前Sheet应选中的单元格
  176. * @param obj: 创建Spread的Dom元素(jquery-contextmenu.build方法的第一个变量可读取)
  177. * @param e: jquery-contextmenu.build方法的第二个变量
  178. * @param {GC.Spread.Sheets.Workbook} spread
  179. * @returns {*}
  180. */
  181. safeRightClickSelection: function (obj, e, spread) {
  182. const sheet = spread.getActiveSheet();
  183. const selections = sheet.getSelections(), target = this.getHitTest(obj, e, sheet), range = this.getTargetSelection(sheet, target);
  184. if (!this.checkTargetInSelection(selections, range)) {
  185. sheet.setSelection(range.row, range.col, range.rowCount, range.colCount);
  186. }
  187. return target;
  188. },
  189. /**
  190. * 获取写入sheet的数据序列
  191. * data:sheet.zh_data, tree: sheet.zh_tree.nodes
  192. * @param sheet
  193. * @returns {*}
  194. */
  195. getSortData: function (sheet) {
  196. if (sheet.zh_dataType) {
  197. if (sheet.zh_dataType === this.DataType.Data) {
  198. return sheet.zh_data;
  199. } else if (sheet.zh_dataType === this.DataType.Tree) {
  200. return sheet.zh_tree.nodes;
  201. } else {
  202. return null;
  203. }
  204. } else {
  205. return null;
  206. }
  207. },
  208. /**
  209. * sheet中 使用delete键,触发EndEdited事件
  210. * @param {GC.Spreads.Sheets.Workbook} spread
  211. * @param {function} fun
  212. */
  213. addDeleteBind: function (spread, fun) {
  214. spread.commandManager().register('deleteEvent', function () {
  215. fun(spread.getActiveSheet());
  216. });
  217. spread.commandManager().setShortcutKey(null, GC.Spread.Commands.Key.del, false, false, false, false);
  218. spread.commandManager().setShortcutKey('deleteEvent', GC.Spread.Commands.Key.del, false, false, false, false);
  219. },
  220. _initSheetDeafult: function (sheet) {
  221. if (sheet.zh_setting.headerFont) {
  222. const vStyle = new spreadNS.Style();
  223. vStyle.font = sheet.zh_setting.headerFont;
  224. sheet.setDefaultStyle(vStyle, spreadNS.SheetArea.colHeader);
  225. }
  226. if (sheet.zh_setting.font) {
  227. const vStyle = new spreadNS.Style();
  228. vStyle.font = sheet.zh_setting.font;
  229. sheet.setDefaultStyle(vStyle, spreadNS.SheetArea.viewport);
  230. }
  231. },
  232. /**
  233. * 根据sheet.zh_setting初始化sheet表头
  234. * @param {GC.Spread.Sheets.Worksheet} sheet
  235. */
  236. _initSheetHeader: function (sheet) {
  237. if (!sheet.zh_setting) { return; }
  238. sheet.setColumnCount(sheet.zh_setting.cols.length);
  239. sheet.setRowCount(sheet.zh_setting.headRows, spreadNS.SheetArea.colHeader);
  240. for (let iRow = 0; iRow < sheet.zh_setting.headRowHeight.length; iRow ++) {
  241. sheet.setRowHeight(iRow, sheet.zh_setting.headRowHeight[iRow], spreadNS.SheetArea.colHeader);
  242. }
  243. for (let iCol = 0; iCol < sheet.zh_setting.cols.length; iCol++) {
  244. const col = sheet.zh_setting.cols[iCol];
  245. const title = col.title.split('|');
  246. const colSpan = col.colSpan ? col.colSpan.split('|'): ['1'], rowSpan = col.rowSpan ? col.rowSpan.split('|'): ['1'];
  247. for (let i = 0; i < title.length; i++) {
  248. const cell = sheet.getCell(i, iCol, spreadNS.SheetArea.colHeader);
  249. cell.text(title[i]).wordWrap(true);
  250. if ((colSpan[i] !== '' && colSpan[i] !== '1') || (rowSpan[i] !== '' && rowSpan[i] !== '1')) {
  251. sheet.addSpan(i, iCol, parseInt(rowSpan[i]), parseInt(colSpan[i]), spreadNS.SheetArea.colHeader);
  252. }
  253. }
  254. sheet.setColumnWidth(iCol, col.width);
  255. if (col.visible !== undefined && col.visible !== null) {
  256. sheet.setColumnVisible(iCol, col.visible);
  257. }
  258. }
  259. sheet.rowOutlines.direction(spreadNS.Outlines.OutlineDirection.backward);
  260. sheet.showRowOutline(false);
  261. if (sheet.zh_setting.defaultRowHeight) {
  262. sheet.defaults.rowHeight = sheet.zh_setting.defaultRowHeight;
  263. }
  264. },
  265. /**
  266. * 初始化sheet, 设置sheet.zh_setting, 并初始化表头
  267. * @param {GC.Spread.Sheets.Worksheet} sheet
  268. * @param setting
  269. */
  270. initSheet: function (sheet, setting) {
  271. this.beginMassOperation(sheet);
  272. sheet.zh_setting = setting;
  273. this._initSheetDeafult(sheet);
  274. this._initSheetHeader(sheet);
  275. sheet.setRowCount(sheet.zh_setting.emptyRows);
  276. sheet.extendCellType = {};
  277. sheet.getRange(0, 0, sheet.getRowCount(), sheet.getColumnCount()).locked(setting.readOnly);
  278. this.endMassOperation(sheet);
  279. },
  280. _loadRowData: function (sheet, data, row) {
  281. // 单元格重新写入数据
  282. if (!data) { return }
  283. sheet.zh_setting.cols.forEach(function (col, j) {
  284. const cell = sheet.getCell(row, j);
  285. if (col.getValue && Object.prototype.toString.apply(col.getValue) === "[object Function]") {
  286. cell.value(col.getValue(data));
  287. } else if (col.field !== '' && data[col.field]) {
  288. cell.value(data[col.field]);
  289. }
  290. if (col.font) {
  291. cell.font(col.font);
  292. }
  293. if (col.foreColor) {
  294. cell.foreColor(col.foreColor);
  295. }
  296. if (col.readOnly && Object.prototype.toString.apply(col.readOnly) === "[object Function]") {
  297. cell.locked(col.readOnly(data) || sheet.zh_setting.readOnly || false).vAlign(1).hAlign(col.hAlign);
  298. } else {
  299. cell.locked(col.readOnly || sheet.zh_setting.readOnly || false).vAlign(1).hAlign(col.hAlign);
  300. }
  301. if (col.formatter) {
  302. cell.formatter(col.formatter);
  303. }
  304. if (sheet.zh_setting.getColor && Object.prototype.toString.apply(sheet.zh_setting.getColor) === "[object Function]") {
  305. cell.backColor(sheet.zh_setting.getColor(data, col, sheet.getDefaultStyle().backColor));
  306. }
  307. });
  308. },
  309. _defineColCellType: function (sheet, col, colSetting) {
  310. if(colSetting.cellType === 'ellipsis') {
  311. if (!sheet.extendCellType.ellipsis) {
  312. sheet.extendCellType.ellipsis = this.CellType.getEllipsisTextCellType();
  313. }
  314. sheet.getRange(-1, col, -1, 1).cellType(sheet.extendCellType.ellipsis);
  315. }
  316. if(colSetting.cellType === 'html') {
  317. if (!sheet.extendCellType.html) {
  318. sheet.extendCellType.html = this.CellType.getHtmlCellType();
  319. }
  320. sheet.getRange(-1, col, -1, 1).cellType(sheet.extendCellType.html);
  321. }
  322. if (colSetting.cellType === 'image') {
  323. if (!sheet.extendCellType.image) {
  324. sheet.extendCellType.image = this.CellType.getImageCellType();
  325. }
  326. sheet.getRange(-1, col, -1, 1).cellType(sheet.extendCellType.image);
  327. }
  328. if (colSetting.cellType === 'imageBtn') {
  329. if (!sheet.extendCellType.image) {
  330. sheet.extendCellType.imageBtn = this.CellType.getImageButtonCellType();
  331. }
  332. sheet.getRange(-1, col, -1, 1).cellType(sheet.extendCellType.imageBtn);
  333. }
  334. if (colSetting.cellType === 'tree') {
  335. if (!sheet.extendCellType.tree) {
  336. sheet.extendCellType.tree = this.CellType.getTreeNodeCellType();
  337. }
  338. sheet.getRange(-1, col, -1, 1).cellType(sheet.extendCellType.tree);
  339. }
  340. if (colSetting.cellType === 'tip') {
  341. if (!sheet.extendCellType.tip) {
  342. sheet.extendCellType.tip = this.CellType.getTipCellType();
  343. }
  344. sheet.getRange(-1, col, -1, 1).cellType(sheet.extendCellType.tip);
  345. }
  346. if (colSetting.cellType === 'checkbox') {
  347. if (!sheet.extendCellType.checkbox) {
  348. sheet.extendCellType.checkbox = new spreadNS.CellTypes.CheckBox();
  349. }
  350. sheet.getRange(-1, col, -1, 1).cellType(sheet.extendCellType.checkbox);
  351. }
  352. if (colSetting.cellType === 'unit') {
  353. if (!sheet.extendCellType.unit) {
  354. sheet.extendCellType.unit = this.CellType.getUnitCellType();
  355. }
  356. sheet.getRange(-1, col, -1, 1).cellType(sheet.extendCellType.unit);
  357. }
  358. if (colSetting.formatter) {
  359. sheet.getRange(-1, col, -1, 1).formatter(colSetting.formatter);
  360. }
  361. },
  362. /**
  363. * 整个sheet重新加载数据
  364. * @param {GC.Spread.Sheets.Worksheet} sheet
  365. */
  366. reLoadSheetData: function (sheet) {
  367. const self = this;
  368. const sortData = sheet.zh_dataType === 'tree' ? sheet.zh_tree.nodes : sheet.zh_data;
  369. this.beginMassOperation(sheet);
  370. try {
  371. sheet.clear(0, 0, sheet.getRowCount(), sheet.getColumnCount(), spreadNS.SheetArea.viewport, spreadNS.StorageType.data);
  372. // 设置总行数
  373. const totalRow = sortData.length + sheet.zh_setting.emptyRows;
  374. sheet.setRowCount(totalRow, spreadNS.SheetArea.viewport);
  375. // 控制空白行
  376. const emptyRows = sheet.getRange(sortData.length, -1, sheet.zh_setting.emptyRows, -1);
  377. emptyRows.locked(sheet.zh_dataType === 'tree');
  378. if (sortData) {
  379. // 单元格写入数据
  380. sortData.forEach(function (data, i) {
  381. self._loadRowData(sheet, data, i);
  382. sheet.setRowVisible(i, data.visible);
  383. });
  384. }
  385. // 设置列单元格格式
  386. sheet.zh_setting.cols.forEach(function (col, j) {
  387. //if (!col.cellType) { return; }
  388. self._defineColCellType(sheet, j, col);
  389. });
  390. this.endMassOperation(sheet);
  391. } catch (err) {
  392. this.endMassOperation(sheet);
  393. }
  394. },
  395. /**
  396. * 重新加载部分数据行
  397. * @param {GC.Spread.Sheets.Worksheet} sheet
  398. * @param {Number} row
  399. * @param {Number} count
  400. */
  401. reLoadRowData: function (sheet, row, count = 1) {
  402. //if (row < 0) { return; }
  403. const self = this;
  404. const sortData = sheet.zh_dataType === 'tree' ? sheet.zh_tree.nodes : sheet.zh_data;
  405. this.beginMassOperation(sheet);
  406. try {
  407. // 清空原单元格数据
  408. sheet.clear(row, -1, count, -1, spreadNS.SheetArea.viewport, spreadNS.StorageType.data);
  409. // 单元格重新写入数据
  410. for (let i = row; i < row + count; i++) {
  411. const data = sortData[i];
  412. if (!data) { continue; }
  413. this._loadRowData(sheet, data, i);
  414. }
  415. this.endMassOperation(sheet);
  416. } catch (err) {
  417. this.endMassOperation(sheet);
  418. }
  419. },
  420. /**
  421. * 重新加载部分行数据
  422. * @param {GC.Spread.Sheets.Worksheet} sheet
  423. * @param {Array} rows
  424. */
  425. reLoadRowsData: function (sheet, rows) {
  426. const self = this;
  427. const sortData = sheet.zh_dataType === 'tree' ? sheet.zh_tree.nodes : sheet.zh_data;
  428. this.beginMassOperation(sheet);
  429. try {
  430. for (const row of rows) {
  431. if (row < 0) { continue; }
  432. // 清空原单元格数据
  433. sheet.clear(row, -1, 1, -1, spreadNS.SheetArea.viewport, spreadNS.StorageType.data);
  434. const data = sortData[row];
  435. // 单元格重新写入数据
  436. this._loadRowData(sheet, data, row);
  437. };
  438. this.endMassOperation(sheet);
  439. } catch (err) {
  440. this.endMassOperation(sheet);
  441. }
  442. },
  443. /**
  444. * 重新加载部分列数据
  445. * @param {GC.Spread.Sheets.Worksheet} sheet
  446. * @param {Array} cols
  447. */
  448. reLoadColsData: function (sheet, cols) {
  449. const self = this;
  450. const sortData = sheet.zh_dataType === 'tree' ? sheet.zh_tree.nodes : sheet.zh_data;
  451. this.beginMassOperation(sheet);
  452. try {
  453. for (const iCol of cols) {
  454. // 清空原单元格数据
  455. sheet.clear(-1, iCol, -1, 1, spreadNS.SheetArea.viewport, spreadNS.StorageType.data);
  456. const col = sheet.zh_setting.cols[iCol];
  457. sortData.forEach(function (data, i) {
  458. // 设置值
  459. const cell = sheet.getCell(i, iCol);
  460. if (col.field !== '' && data[col.field]) {
  461. cell.value(data[col.field]).locked(col.readOnly || sheet.zh_setting.readOnly || false).vAlign(1).hAlign(col.hAlign);
  462. } else {
  463. cell.locked(col.readOnly || sheet.zh_setting.readOnly || false).vAlign(1).hAlign(col.hAlign);
  464. }
  465. // 设置单元格格式
  466. if (col.formatter) {
  467. cell.formatter(col.formatter);
  468. }
  469. });
  470. }
  471. this.endMassOperation(sheet);
  472. } catch (err) {
  473. this.endMassOperation(sheet);
  474. }
  475. },
  476. reLoadNodesData: function (sheet, nodes) {
  477. this.beginMassOperation(sheet);
  478. nodes = nodes instanceof Array ? nodes : [nodes];
  479. for (const node of nodes) {
  480. const sortData = sheet.zh_dataType === 'tree' ? sheet.zh_tree.nodes : sheet.zh_data;
  481. this._loadRowData(sheet, node, sortData.indexOf(node));
  482. }
  483. this.endMassOperation(sheet);
  484. },
  485. /**
  486. * 根据data加载sheet数据,合并了一般数据和树结构数据的加载
  487. * @param {GC.Spread.Sheets.Worksheet} sheet
  488. * @param {String} dataType - 1.'zh_data' 2.'zh_tree'
  489. * @param {Array|PathTree} data - 对dataType对应
  490. */
  491. loadSheetData: function (sheet, dataType, data){
  492. sheet.zh_dataType = dataType;
  493. if (dataType === 'tree') {
  494. sheet.zh_tree = data;
  495. } else {
  496. sheet.zh_data = data;
  497. }
  498. this.protectedSheet(sheet);
  499. this.reLoadSheetData(sheet);
  500. },
  501. /**
  502. * 获取复制数据HTML格式(过滤不可见单元格)
  503. * @param {GC.Spread.Sheets.Worksheet} sheet
  504. * @returns {string}
  505. */
  506. getFilterCopyHTML: function (sheet) {
  507. const sel = sheet.getSelections()[0];
  508. const html = [];
  509. html.push('<table>');
  510. for (let i = sel.row, iLen = sel.row + sel.rowCount; i < iLen; i++) {
  511. // 跳过隐藏行
  512. if (!sheet.getCell(i, -1).visible()) { continue; }
  513. const rowHtml = [];
  514. rowHtml.push('<tr>');
  515. for (let j = sel.col, jLen = sel.col + sel.colCount; j < jLen; j++) {
  516. const data = sheet.getText(i, j);
  517. rowHtml.push('<td>' + data + '</td>');
  518. }
  519. rowHtml.push('</tr>');
  520. html.push(rowHtml.join(''));
  521. }
  522. html.push('</table>');
  523. return html.join('');
  524. },
  525. /**
  526. * 获取复制数据Text格式(过滤不可见单元格)
  527. * @param {GC.Spread.Sheets.Worksheet} sheet
  528. * @returns {string}
  529. */
  530. getFilterCopyText: function (sheet) {
  531. const copyData = [];
  532. const sel = sheet.getSelections()[0];
  533. for(let i = sel.row, iLen = sel.row + sel.rowCount; i < iLen; i++) {
  534. // 跳过隐藏行
  535. if (!sheet.getCell(i, -1).visible()) { continue; }
  536. const rowText = [];
  537. for (let j = sel.col, jLen = sel.col + sel.colCount; j < jLen; j++) {
  538. const data = sheet.getText(i, j);
  539. rowText.push(data);
  540. }
  541. copyData.push(rowText.join('\t'));
  542. }
  543. return copyData.join('\n');
  544. },
  545. /**
  546. * 树表结构,定位至指定的节点
  547. * @param {GC.Spread.Sheets.Worksheet} sheet - 需要定位的sheet
  548. * @param {Number} id - 定位节点的id
  549. */
  550. locateTreeNode: function (sheet, id) {
  551. const tree = sheet.zh_tree;
  552. if (!tree) { return }
  553. const node = tree.getItems(id);
  554. if (!node) { return }
  555. const index = tree.nodes.indexOf(node);
  556. const sels = sheet.getSelections();
  557. sheet.setSelection(index, sels[0].col, 1, 1);
  558. sheet.showRow(index, spreadNS.VerticalPosition.center);
  559. },
  560. /**
  561. * 获取当前选行的数据对象
  562. * @param {GC.Spread.Sheets.Worksheet} sheet
  563. * @returns {Object}
  564. */
  565. getSelectObject: function (sheet) {
  566. if (!sheet) {
  567. return null;
  568. } else if (sheet.zh_dataType) {
  569. const sel = sheet.getSelections()[0];
  570. if (sheet.zh_dataType === this.DataType.Tree) {
  571. return sheet.zh_tree.nodes[sel.row];
  572. } else if (sheet.zh_dataType === this.DataType.Data) {
  573. return sheet.zh_data[sel.row];
  574. } else {
  575. return null;
  576. }
  577. }
  578. },
  579. /**
  580. * 刷新列显示
  581. * @param sheet
  582. */
  583. refreshColumnVisible: function (sheet) {
  584. if(sheet.zh_setting) {
  585. sheet.zh_setting.cols.forEach(function (col, index) {
  586. if (col.visible !== undefined && col.visible !== null) {
  587. sheet.setColumnVisible(index, col.visible);
  588. }
  589. });
  590. }
  591. },
  592. /**
  593. * 刷新行显示
  594. * @param sheet
  595. */
  596. refreshTreeRowVisible: function (sheet) {
  597. this.beginMassOperation(sheet);
  598. const sortData = sheet.zh_dataType === this.DataType.Data ? sheet.zh_data : sheet.zh_tree.nodes;
  599. for (const iRow in sortData) {
  600. const node = sortData[iRow];
  601. if (node.visible !== undefined && node.visible !== null) {
  602. sheet.setRowVisible(iRow, node.visible);
  603. } else {
  604. sheet.setRowVisible(iRow, true);
  605. }
  606. }
  607. // if (sheet.zh_tree) {
  608. // for (const iRow in sheet.zh_tree.nodes) {
  609. // const node = sheet.zh_tree.nodes[iRow];
  610. // if (node.visible !== undefined && node.visible !== null) {
  611. // sheet.setRowVisible(iRow, node.visible);
  612. // } else {
  613. // sheet.setRowVisible(iRow, true);
  614. // }
  615. // }
  616. // }
  617. this.endMassOperation(sheet);
  618. },
  619. refreshColumnAlign: function (sheet) {
  620. if (sheet.zh_setting) {
  621. for (const iCol in sheet.zh_setting.cols) {
  622. const col = sheet.zh_setting.cols[iCol];
  623. sheet.getRange(-1, iCol, -1, 1).hAlign(col.hAlign);
  624. }
  625. }
  626. },
  627. /**
  628. * 刷新列是否只读
  629. * @param sheet
  630. * @param field
  631. * @param readonly
  632. */
  633. resetFieldReadOnly: function (sheet, field, readonly) {
  634. const fields = field instanceof Array ? field : [field];
  635. if (sheet.zh_setting) {
  636. sheet.zh_setting.cols.forEach(function (col, i) {
  637. if (fields.indexOf(col.field) !== -1) {
  638. col.readOnly = readonly;
  639. sheet.getRange(-1, i, -1, 1).locked(col.readOnly || sheet.zh_setting.readOnly || false);
  640. }
  641. });
  642. }
  643. },
  644. CellType: {
  645. /**
  646. * 获取树结构CellType
  647. * 通过SpreadJsObj.loadSheetData(sheet, 'tree', tree)加载树结构数据
  648. * 要求tree类型为PathTree, 节点必须含有{id, pid, level, order, is_leaf}数据
  649. * @returns {TreeNodeCellType}
  650. */
  651. getTreeNodeCellType: function () {
  652. const indent = 20;
  653. const levelIndent = -5;
  654. const halfBoxLength = 5;
  655. const halfExpandLength = 3;
  656. /**
  657. * 画一条点线段
  658. * @param canvas - 画布
  659. * @param x1 - 线段起点 x
  660. * @param y1 - 线段起点 y
  661. * @param x2 - 线段终点 x
  662. * @param y2 - 线段终点 y
  663. * @param color - 线段颜色
  664. */
  665. const drawDotLine = function (canvas, x1, y1, x2, y2, color) {
  666. canvas.save();
  667. // 设置偏移量
  668. canvas.translate(0.5, 0.5);
  669. canvas.beginPath();
  670. canvas.strokeStyle = color;
  671. canvas.dottedLine(x1, y1, x2, y2);
  672. canvas.stroke();
  673. canvas.restore();
  674. };
  675. /**
  676. * 画一条线段
  677. * @param canvas - 画布
  678. * @param x1 - 线段起点 x
  679. * @param y1 - 线段起点 y
  680. * @param x2 - 线段终点 x
  681. * @param y2 - 线段终点 y
  682. * @param color - 线段颜色
  683. */
  684. const drawLine = function (canvas, x1, y1, x2, y2, color) {
  685. canvas.save();
  686. // 设置偏移量
  687. canvas.translate(0.5, 0.5);
  688. canvas.beginPath();
  689. canvas.moveTo(x1, y1);
  690. canvas.lineTo(x2, y2);
  691. canvas.strokeStyle = color;
  692. canvas.stroke();
  693. canvas.restore();
  694. };
  695. /**
  696. * 画一个方框
  697. * @param {Object} canvas - 画布
  698. * @param {Object} rect - 方框区域
  699. * @param {String} lineColor - 画线颜色
  700. * @param {String} fillColor - 填充颜色
  701. */
  702. const drawBox = function (canvas, rect, lineColor, fillColor) {
  703. canvas.save();
  704. // 设置偏移量
  705. canvas.translate(0.5, 0.5);
  706. canvas.strokeStyle = lineColor;
  707. canvas.beginPath();
  708. canvas.moveTo(rect.left, rect.top);
  709. canvas.lineTo(rect.left, rect.bottom);
  710. canvas.lineTo(rect.right, rect.bottom);
  711. canvas.lineTo(rect.right, rect.top);
  712. canvas.lineTo(rect.left, rect.top);
  713. canvas.stroke();
  714. canvas.fillStyle = fillColor;
  715. canvas.fill();
  716. canvas.restore();
  717. };
  718. /**
  719. * 画树结构-展开收起按钮
  720. * @param {Object} canvas - 画布
  721. * @param {Number} x - 单元格左顶点坐标 x
  722. * @param {Number} y - 单元格左顶点坐标 y
  723. * @param {Number} w - 单元格宽度
  724. * @param {Number} h - 单元格高度
  725. * @param {Number} centerX - 按钮中央坐标
  726. * @param {Number} centerY - 按钮中央坐标
  727. * @param {Boolean} expanded - 当前节点展开收起状态
  728. */
  729. const drawExpandBox = function (canvas, x, y, w, h, centerX, centerY, expanded) {
  730. let rect = {
  731. top: centerY - halfBoxLength,
  732. bottom: centerY + halfBoxLength,
  733. left: centerX - halfBoxLength,
  734. right: centerX + halfBoxLength
  735. };
  736. let h1, h2, offset = 1;
  737. if (rect.left < x + w) {
  738. // 方框超出单元格宽度时,超出部分不画。
  739. rect.right = Math.min(rect.right, x + w);
  740. drawBox(canvas, rect, '#808080', 'white');
  741. // 画中心十字
  742. // 画十字横线
  743. h1 = centerX - halfExpandLength;
  744. h2 = Math.min(centerX + halfExpandLength, x + w);
  745. if (h2 > h1) {
  746. drawLine(canvas, h1, centerY, h2, centerY, '#808080');
  747. }
  748. // 画十字竖线
  749. if (!expanded && (centerX < x + w)) {
  750. drawLine(canvas, centerX, centerY - halfExpandLength, centerX, centerY + halfExpandLength, '#808080');
  751. }
  752. }
  753. };
  754. let TreeNodeCellType = function (){};
  755. TreeNodeCellType.prototype = new spreadNS.CellTypes.Text();
  756. const proto = TreeNodeCellType.prototype;
  757. /**
  758. * 绘制方法
  759. * @param {Object} canvas - 画布
  760. * @param value - cell.value
  761. * @param {Number} x - 单元格左顶点坐标 x
  762. * @param {Number} y - 单元格左顶点坐标 y
  763. * @param {Number} w - 单元格宽度
  764. * @param {Number} h - 单元格高度
  765. * @param {Object} style - cell.style
  766. * @param {Object} options
  767. */
  768. proto.paint = function (canvas, value, x, y, w, h, style, options) {
  769. // 清理 画布--单元格范围 旧数据
  770. if (style.backColor) {
  771. canvas.save();
  772. canvas.fillStyle = style.backColor;
  773. canvas.fillRect(x, y, w, h);
  774. canvas.restore();
  775. } else {
  776. canvas.clearRect(x, y, w, h);
  777. }
  778. const tree = options.sheet.zh_tree;
  779. // 使用TreeCellType前,需定义sheet.tree
  780. if (tree) {
  781. const node = options.row < tree.nodes.length ? tree.nodes[options.row] : null;
  782. if (node) {
  783. const showTreeLine = true;
  784. const centerX = Math.floor(x) + (node.level) * indent + (node.level) * levelIndent + indent / 2;
  785. const centerY = Math.floor((y + (y + h)) / 2);
  786. // Draw Sibling Line
  787. if (showTreeLine) {
  788. // Draw Horizontal Line
  789. if (centerX < x + w) {
  790. const x1 = centerX + indent / 2;
  791. //drawLine(canvas, centerX, centerY, Math.min(x1, x + w), centerY, 'gray');
  792. drawDotLine(canvas, centerX, centerY, Math.min(x1, x + w), centerY, '#b8b8b8');
  793. }
  794. // Draw Vertical Line
  795. if (centerX < x + w) {
  796. const y1 = tree.isLastSibling(node) ? centerY : y + h;
  797. const parent = tree.getParent(node);
  798. const y2 = y1 - centerY;
  799. if (node.order === 1 && !parent) {
  800. //drawLine(canvas, centerX, centerY, centerX, y1, 'gray');
  801. drawDotLine(canvas, centerX, centerY, centerX, y1, '#b8b8b8');
  802. } else {
  803. //drawLine(canvas, centerX, y, centerX, y1, 'gray');
  804. drawDotLine(canvas, centerX, y, centerX, y1, '#b8b8b8');
  805. }
  806. }
  807. }
  808. // Draw Expand Box
  809. if (!node.is_leaf) {
  810. drawExpandBox(canvas, x, y, w, h, centerX, centerY, node.expanded);
  811. }
  812. // Draw Parent Line
  813. if (showTreeLine) {
  814. let parent = tree.getParent(node), parentCenterX = centerX - indent - levelIndent;
  815. while (parent) {
  816. if (!tree.isLastSibling(parent)) {
  817. if (parentCenterX < x + w) {
  818. //drawLine(canvas, parentCenterX, y, parentCenterX, y + h, 'gray');
  819. drawDotLine(canvas, parentCenterX, y, parentCenterX, y + h, '#b8b8b8');
  820. }
  821. }
  822. parent = tree.getParent(parent);
  823. parentCenterX -= (indent + levelIndent);
  824. }
  825. };
  826. // 重定位x
  827. const move = (node.level + 1) * indent + (node.level) * levelIndent;
  828. x = x + move;
  829. w = w - move;
  830. }
  831. }
  832. // Drawing Text
  833. spreadNS.CellTypes.Text.prototype.paint.apply(this, [canvas, value, x, y, w, h, style, options]);
  834. };
  835. /**
  836. * 获取点击信息
  837. * @param {Number} x
  838. * @param {Number} y
  839. * @param {Object} cellStyle
  840. * @param {Object} cellRect
  841. * @param {Object} context
  842. * @returns {{x: *, y: *, row: *, col: *|boolean|*[]|number|{}|UE.dom.dtd.col, cellStyle: *, cellRect: *, sheet: *|StyleSheet, sheetArea: *}}
  843. */
  844. proto.getHitInfo = function (x, y, cellStyle, cellRect, context) {
  845. return {
  846. x: x,
  847. y: y,
  848. row: context.row,
  849. col: context.col,
  850. cellStyle: cellStyle,
  851. cellRect: cellRect,
  852. sheet: context.sheet,
  853. sheetArea: context.sheetArea
  854. };
  855. };
  856. /**
  857. * 鼠标点击 树结构按钮 响应展开收起(未加载子节点时,先加载子节点)
  858. * @param {Object} hitinfo - 见getHitInfo
  859. */
  860. proto.processMouseDown = function (hitinfo) {
  861. const offset = -1;
  862. const tree = hitinfo.sheet.zh_tree;
  863. if (!tree) { return; }
  864. const node = tree.nodes[hitinfo.row];
  865. if (!node) { return; }
  866. let centerX = hitinfo.cellRect.x + offset + (node.level) * indent + (node.level) * levelIndent + indent / 2;
  867. let centerY = (hitinfo.cellRect.y + offset + (hitinfo.cellRect.y + offset + hitinfo.cellRect.height)) / 2;
  868. // 点击展开节点时,如果已加载子项,则展开,反之这加载子项,展开
  869. if (Math.abs(hitinfo.x - centerX) < halfBoxLength && Math.abs(hitinfo.y - centerY) < halfBoxLength) {
  870. const children = tree.getChildren(node);
  871. if (!node.expanded && !node.is_leaf && children.length === 0 && tree.loadChildren) {
  872. tree.loadChildren(node, function () {
  873. node.expanded = true;
  874. const children = tree.getChildren(node);
  875. hitinfo.sheet.addRows(hitinfo.row + 1, children.length);
  876. SpreadJsObj.reLoadRowData(hitinfo.sheet, hitinfo.row + 1, children.length);
  877. });
  878. } else {
  879. tree.setExpanded(node, !node.expanded);
  880. SpreadJsObj.massOperationSheet(hitinfo.sheet, function () {
  881. const posterity = tree.getPosterity(node);
  882. for (const child of posterity) {
  883. hitinfo.sheet.setRowVisible(tree.nodes.indexOf(child), child.visible, hitinfo.sheetArea);
  884. }
  885. });
  886. hitinfo.sheet.repaint();
  887. }
  888. }
  889. };
  890. return new TreeNodeCellType();
  891. },
  892. /**
  893. * 获取 带悬浮提示的CellType
  894. * @returns {TipCellType}
  895. */
  896. getTipCellType: function () {
  897. const TipCellType = function () {};
  898. // 继承 SpreadJs定义的 普通的TextCellType
  899. TipCellType.prototype = new spreadNS.CellTypes.Text();
  900. const proto = TipCellType.prototype;
  901. /**
  902. * 获取点击信息
  903. * @param {Number} x
  904. * @param {Number} y
  905. * @param {Object} cellStyle
  906. * @param {Object} cellRect
  907. * @param {Object} context
  908. * @returns {{x: *, y: *, row: *, col: *|boolean|*[]|number|{}|UE.dom.dtd.col, cellStyle: *, cellRect: *, sheet: *|StyleSheet, sheetArea: *}}
  909. */
  910. proto.getHitInfo = function (x, y, cellStyle, cellRect, context) {
  911. return {
  912. x: x,
  913. y: y,
  914. row: context.row,
  915. col: context.col,
  916. cellStyle: cellStyle,
  917. cellRect: cellRect,
  918. sheet: context.sheet,
  919. sheetArea: context.sheetArea
  920. };
  921. };
  922. /**
  923. * 鼠标进入单元格事件 - 显示悬浮提示
  924. * @param {Object} hitinfo - 见getHitInfo返回值
  925. */
  926. proto.processMouseEnter = function (hitinfo) {
  927. const text = hitinfo.sheet.getText(hitinfo.row, hitinfo.col);
  928. const setting = hitinfo.sheet.setting;
  929. if (setting.pos && text && text !== '') {
  930. if (!this._toolTipElement) {
  931. let div = $('#autoTip')[0];
  932. if (!div) {
  933. div = document.createElement("div");
  934. $(div).css("position", "absolute")
  935. .css("border", "1px #C0C0C0 solid")
  936. .css("box-shadow", "1px 2px 5px rgba(0,0,0,0.4)")
  937. .css("font", "9pt Arial")
  938. .css("background", "white")
  939. .css("padding", 5)
  940. .attr("id", 'autoTip');
  941. $(div).hide();
  942. document.body.insertBefore(div, null);
  943. }
  944. this._toolTipElement = div;
  945. $(this._toolTipElement).text(text).css("top", setting.pos.y + hitinfo.y + 15).css("left", setting.pos.x + hitinfo.x + 15);
  946. $(this._toolTipElement).show("fast");
  947. }
  948. }
  949. };
  950. /**
  951. * 鼠标移出单元格事件 - 隐藏悬浮提示
  952. * @param {Object} hitinfo - 见getHitInfo返回值
  953. */
  954. proto.processMouseLeave = function (hitinfo) {
  955. if (this._toolTipElement) {
  956. $(this._toolTipElement).hide();
  957. this._toolTipElement = null;
  958. }
  959. };
  960. return new TipCellType();
  961. },
  962. /**
  963. * 获取 带图片的cellType(图片需在document中定义好img,并写入col的img属性)
  964. *
  965. * img:
  966. * 1. 整列固定,则传入img的select
  967. * e.g. {title: '附件', field: 'attachment', cellType: 'image', img = '#attachment-img'}
  968. *
  969. * 2. 各单元格自定义,则
  970. * e.g. {title: '附件', field: 'attachment', cellType: 'image', img = getAttachmentImage}
  971. * function getAttachmentImage (data) {
  972. * $('#attachment-img').url = data.attachmentImageUrl;
  973. * return $('#attachment-img')[0];
  974. * }
  975. *
  976. * @returns {ImageCellType}
  977. */
  978. getImageCellType: function () {
  979. const ImageCellType = function (){};
  980. ImageCellType.prototype = new spreadNS.CellTypes.Text();
  981. const proto = ImageCellType.prototype;
  982. proto.getImage = function (sheet, iRow, iCol) {
  983. const col = sheet.zh_setting.cols[iCol];
  984. let imgSource = col.img;
  985. if (imgSource && Object.prototype.toString.apply(imgSource) === "[object Function]") {
  986. const sortData = SpreadJsObj.getSortData(sheet);
  987. const data = sortData ? sortData[iRow] : null;
  988. return data ? imgSource(data) : null;
  989. } else {
  990. return $(imgSource)[0] ? $(imgSource)[0] : null;
  991. }
  992. };
  993. proto.paint = function (canvas, value, x, y, w, h, style, options) {
  994. const col = options.sheet.zh_setting.cols[options.col];
  995. const img = this.getImage(options.sheet, options.row, options.col);
  996. const indent = col.indent ? col.indent : 10;
  997. if (img) {
  998. if (style.backColor) {
  999. canvas.save();
  1000. canvas.fillStyle = style.backColor;
  1001. canvas.fillRect(x, y, indent + img.width, h);
  1002. canvas.restore();
  1003. }
  1004. canvas.drawImage(img, x + indent, y + (h - img.height) / 2);
  1005. if (style.hAlign !== spreadNS.HorizontalAlign.left) {
  1006. style.hAlign = spreadNS.HorizontalAlign.left;
  1007. }
  1008. x = x + indent + img.width;
  1009. w = w - indent - img.width;
  1010. }
  1011. // Drawing Text
  1012. spreadNS.CellTypes.Text.prototype.paint.apply(this, [canvas, value, x, y, w, h, style, options]);
  1013. };
  1014. /**
  1015. * 获取点击信息
  1016. * @param {Number} x
  1017. * @param {Number} y
  1018. * @param {Object} cellStyle
  1019. * @param {Object} cellRect
  1020. * @param {Object} context
  1021. * @returns {{x: *, y: *, row: *, col: *|boolean|*[]|number|{}|UE.dom.dtd.col, cellStyle: *, cellRect: *, sheet: *|StyleSheet, sheetArea: *}}
  1022. */
  1023. proto.getHitInfo = function (x, y, cellStyle, cellRect, context) {
  1024. return {
  1025. x: x,
  1026. y: y,
  1027. row: context.row,
  1028. col: context.col,
  1029. cellStyle: cellStyle,
  1030. cellRect: cellRect,
  1031. sheet: context.sheet,
  1032. sheetArea: context.sheetArea
  1033. };
  1034. };
  1035. /**
  1036. * 鼠标点击
  1037. * @param {Object} hitinfo - 见getHitInfo
  1038. */
  1039. proto.processMouseDown = function (hitinfo) {
  1040. const img = this.getImage(hitinfo.sheet, hitinfo.row, hitinfo.col);
  1041. if (img) {
  1042. const halfX = img.width / 2, halfY = img.height / 2;
  1043. const centerX = hitinfo.cellRect.x + indent + halfX;
  1044. const centerY = hitinfo.cellRect.y + hitinfo.cellRect.height / 2;
  1045. // 点击展开节点时,如果已加载子项,则展开,反之这加载子项,展开
  1046. if (Math.abs(hitinfo.x - centerX) < halfX && Math.abs(hitinfo.y - centerY) < halfY) {
  1047. const imageClick = hitinfo.sheet.zh_setting ? hitinfo.sheet.zh_setting.imageClick : null;
  1048. if (imageClick && Object.prototype.toString.apply(imageClick) === "[object Function]") {
  1049. const sortData = SpreadJsObj.getSortData(hitinfo.sheet);
  1050. const data = sortData ? sortData[hitinfo.row] : null;
  1051. imageClick(data);
  1052. }
  1053. }
  1054. }
  1055. };
  1056. return new ImageCellType();
  1057. },
  1058. /**
  1059. *
  1060. * 获取 带normal-hover-active按钮的cellType(需定义三张图片,须在document中定义好img,并写入col的normalImg, hoverImg, activeImg属性)
  1061. * 其中:normalImg必需,向下套用(不存在activeImg则使用hoverImg,不存在hoverImg则使用normalImg)
  1062. * 三个img均可像getImageCellType一样动态获取,参见getImageCellType注释
  1063. *
  1064. * @returns {ImageCellType}
  1065. */
  1066. getImageButtonCellType: function () {
  1067. let hover = 1, active = 2;
  1068. const ImageCellType = function (){};
  1069. ImageCellType.prototype = new spreadNS.CellTypes.Text();
  1070. const proto = ImageCellType.prototype;
  1071. proto.getImage = function (sheet, iRow, iCol) {
  1072. const col = sheet.zh_setting.cols[iCol];
  1073. let imgSource = col.normalImg;
  1074. const cell = sheet.getCell(iRow, iCol), tag = cell.tag();
  1075. if (tag === active) {
  1076. imgSource = col.activeImg ? col.activeImg : (col.hoverImg ? col.hoverImg : col.normalImg);
  1077. } else if (tag === hover) {
  1078. imgSource = col.hoverImg ? col.hoverImg : col.normalImg;
  1079. }
  1080. if (imgSource && Object.prototype.toString.apply(imgSource) === "[object Function]") {
  1081. const sortData = SpreadJsObj.getSortData(sheet);
  1082. const data = sortData ? sortData[iRow] : null;
  1083. return data ? imgSource(data) : null;
  1084. } else {
  1085. return $(imgSource)[0] ? $(imgSource)[0] : null;
  1086. }
  1087. };
  1088. proto.paint = function (canvas, value, x, y, w, h, style, options) {
  1089. const col = options.sheet.zh_setting.cols[options.col];
  1090. const sortData = SpreadJsObj.getSortData(options.sheet);
  1091. const data = sortData ? sortData[options.row] : null;
  1092. let showImage = true;
  1093. if (col.showImage && Object.prototype.toString.apply(col.showImage) === "[object Function]") {
  1094. showImage = col.showImage(data);
  1095. }
  1096. const img = showImage ? this.getImage(options.sheet, options.row, options.col) : null;
  1097. const indent = col.indent ? col.indent : 10;
  1098. if (style.hAlign === spreadNS.HorizontalAlign.right) {
  1099. if (img) {
  1100. if (style.backColor) {
  1101. canvas.save();
  1102. canvas.fillStyle = style.backColor;
  1103. canvas.fillRect(x + w - indent - img.width, y, img.width, h);
  1104. canvas.restore();
  1105. }
  1106. canvas.drawImage(img, x + w - indent - img.width, y + (h - img.height) / 2);
  1107. w = w - indent - img.width;
  1108. }
  1109. // Drawing Text
  1110. spreadNS.CellTypes.Text.prototype.paint.apply(this, [canvas, value, x, y, w, h, style, options]);
  1111. } else {
  1112. if (img) {
  1113. if (style.backColor) {
  1114. canvas.save();
  1115. canvas.fillStyle = style.backColor;
  1116. canvas.fillRect(x, y, indent + img.width, h);
  1117. canvas.restore();
  1118. }
  1119. canvas.drawImage(img, x + 10, y + (h - img.height) / 2);
  1120. if (style.hAlign !== spreadNS.HorizontalAlign.left) {
  1121. style.hAlign = spreadNS.HorizontalAlign.left;
  1122. }
  1123. x = x + indent + img.width;
  1124. w = w - indent - img.width;
  1125. }
  1126. // Drawing Text
  1127. spreadNS.CellTypes.Text.prototype.paint.apply(this, [canvas, value, x, y, w, h, style, options]);
  1128. }
  1129. };
  1130. /**
  1131. * 获取点击信息
  1132. * @param {Number} x
  1133. * @param {Number} y
  1134. * @param {Object} cellStyle
  1135. * @param {Object} cellRect
  1136. * @param {Object} context
  1137. * @returns {{x: *, y: *, row: *, col: *|boolean|*[]|number|{}|UE.dom.dtd.col, cellStyle: *, cellRect: *, sheet: *|StyleSheet, sheetArea: *}}
  1138. */
  1139. proto.getHitInfo = function (x, y, cellStyle, cellRect, context) {
  1140. return {
  1141. x: x,
  1142. y: y,
  1143. row: context.row,
  1144. col: context.col,
  1145. cellStyle: cellStyle,
  1146. cellRect: cellRect,
  1147. sheet: context.sheet,
  1148. sheetArea: context.sheetArea
  1149. };
  1150. };
  1151. /**
  1152. * 鼠标点击
  1153. * @param {Object} hitinfo - 见getHitInfo
  1154. */
  1155. proto.processMouseEnter = function (hitinfo) {
  1156. const col = hitinfo.sheet.zh_setting.cols[hitinfo.col];
  1157. // Drawing Image
  1158. if (col.hoverImg) {
  1159. const cell = hitinfo.sheet.getCell(hitinfo.row, hitinfo.col);
  1160. cell.tag(hover);
  1161. hitinfo.sheet.repaint(hitinfo.cellRect);
  1162. }
  1163. };
  1164. proto.processMouseLeave = function (hitinfo) {
  1165. const col = hitinfo.sheet.zh_setting.cols[hitinfo.col];
  1166. // Drawing Image
  1167. if (col.hoverImg) {
  1168. const cell = hitinfo.sheet.getCell(hitinfo.row, hitinfo.col);
  1169. cell.tag(null);
  1170. hitinfo.sheet.repaint(hitinfo.cellRect);
  1171. }
  1172. };
  1173. proto.processMouseDown = function (hitinfo) {
  1174. const col = hitinfo.sheet.zh_setting.cols[hitinfo.col];
  1175. if (col.activeImg) {
  1176. const cell = hitinfo.sheet.getCell(hitinfo.row, hitinfo.col);
  1177. cell.tag(active);
  1178. hitinfo.sheet.repaint(hitinfo.cellRect);
  1179. }
  1180. };
  1181. proto.processMouseUp = function (hitinfo) {
  1182. const col = hitinfo.sheet.zh_setting.cols[hitinfo.col];
  1183. const sortData = SpreadJsObj.getSortData(hitinfo.sheet);
  1184. const data = sortData ? sortData[hitinfo.row] : null;
  1185. if (col.showImage && Object.prototype.toString.apply(col.showImage) === "[object Function]") {
  1186. if (!col.showImage(data)) {
  1187. return;
  1188. }
  1189. }
  1190. const imageClick = hitinfo.sheet.zh_setting ? hitinfo.sheet.zh_setting.imageClick : null;
  1191. if (imageClick && Object.prototype.toString.apply(imageClick) === "[object Function]") {
  1192. imageClick(data);
  1193. const cell = hitinfo.sheet.getCell(hitinfo.row, hitinfo.col);
  1194. cell.tag(null);
  1195. hitinfo.sheet.repaint(hitinfo.cellRect);
  1196. }
  1197. };
  1198. /*
  1199. 注释部分以进入鼠标进入图片,点击图片为基准更新图片,鼠标快速移动时,可能失效
  1200. */
  1201. // proto.processMouseDown = function (hitinfo) {
  1202. // const img = this.getImage(hitinfo.sheet, hitinfo.row, hitinfo.col);
  1203. // const halfX = img.width / 2, halfY = img.height / 2;
  1204. // const centerX = hitinfo.cellRect.x + indent + halfX;
  1205. // const centerY = hitinfo.cellRect.y + hitinfo.cellRect.height / 2;
  1206. //
  1207. // if (Math.abs(hitinfo.x - centerX) < halfX && Math.abs(hitinfo.y - centerY) < halfY) {
  1208. // const cell = hitinfo.sheet.getCell(hitinfo.row, hitinfo.col);
  1209. // cell.tag(down);
  1210. // hitinfo.sheet.repaint(hitinfo.cellRect);
  1211. // }
  1212. // };
  1213. // proto.processMouseUp = function (hitinfo) {
  1214. // const img = this.getImage(hitinfo.sheet, hitinfo.row, hitinfo.col);
  1215. // const halfX = img.width / 2, halfY = img.height / 2;
  1216. // const centerX = hitinfo.cellRect.x + indent + halfX;
  1217. // const centerY = hitinfo.cellRect.y + hitinfo.cellRect.height / 2;
  1218. //
  1219. // // 点击展开节点时,如果已加载子项,则展开,反之这加载子项,展开
  1220. // if (Math.abs(hitinfo.x - centerX) < halfX && Math.abs(hitinfo.y - centerY) < halfY) {
  1221. // const imageClick = hitinfo.sheet.zh_setting ? hitinfo.sheet.zh_setting.imageClick : null;
  1222. // if (imageClick && Object.prototype.toString.apply(imageClick) === "[object Function]") {
  1223. // const sortData = SpreadJsObj.getSortData(hitinfo.sheet);
  1224. // const data = sortData ? sortData[hitinfo.row] : null;
  1225. // imageClick(data);
  1226. // const cell = hitinfo.sheet.getCell(hitinfo.row, hitinfo.col);
  1227. // cell.tag(null);
  1228. // hitinfo.sheet.repaint(hitinfo.cellRect);
  1229. // }
  1230. // }
  1231. // };
  1232. // proto.processMouseMove = function (hitinfo) {
  1233. // const img = this.getImage(hitinfo.sheet, hitinfo.row, hitinfo.col);
  1234. // const halfX = img.width / 2, halfY = img.height / 2;
  1235. // const centerX = hitinfo.cellRect.x + indent + halfX;
  1236. // const centerY = hitinfo.cellRect.y + hitinfo.cellRect.height / 2;
  1237. // const cell = hitinfo.sheet.getCell(hitinfo.row, hitinfo.col);
  1238. // if (Math.abs(hitinfo.x - centerX) < halfX && Math.abs(hitinfo.y - centerY) < halfY) {
  1239. // if (cell.tag() !== hover) {
  1240. // cell.tag(hover);
  1241. // hitinfo.sheet.repaint(hitinfo.cellRect);
  1242. // }
  1243. // } else {
  1244. // if (cell.tag() === hover) {
  1245. // cell.tag(null);
  1246. // hitinfo.sheet.repaint(hitinfo.cellRect);
  1247. // }
  1248. // }
  1249. // };
  1250. return new ImageCellType();
  1251. },
  1252. /**
  1253. * 获取 嵌入Html的cellType
  1254. * @returns {HTMLCellType}
  1255. */
  1256. getHtmlCellType: function () {
  1257. const HTMLCellType = function (){};
  1258. HTMLCellType.prototype = new spreadNS.CellTypes.Text;
  1259. const proto = ImageCellType.prototype;
  1260. proto.paint = function (ctx, value, x, y, w, h, style, context) {
  1261. let DOMURL = window.URL || window.webkitURL || window;
  1262. let cell = context.sheet.getCell(context.row, context.col);
  1263. let img = cell.tag();
  1264. if (img) {
  1265. try {
  1266. ctx.save();
  1267. ctx.rect(x, y, w, h);
  1268. ctx.clip();
  1269. ctx.drawImage(img, x + 2, y + 2)
  1270. ctx.restore();
  1271. cell.tag(null);
  1272. return;
  1273. }
  1274. catch (err) {
  1275. GC.Spread.Sheets.CustomCellType.prototype.paint.apply(this, [ctx, "#HTMLError", x, y, w, h, style, context])
  1276. cell.tag(null);
  1277. return;
  1278. }
  1279. }
  1280. let svgPattern = '<svg xmlns="http://www.w3.org/2000/svg" width="{0}" height="{1}">' +
  1281. '<foreignObject width="100%" height="100%"><div xmlns="http://www.w3.org/1999/xhtml" style="font:{2}">{3}</div></foreignObject></svg>';
  1282. let data = svgPattern.replace("{0}", w).replace("{1}", h).replace("{2}", style.font).replace("{3}", value);
  1283. let doc = document.implementation.createHTMLDocument("");
  1284. doc.write(data);
  1285. // Get well-formed markup
  1286. data = (new XMLSerializer()).serializeToString(doc.body.children[0]);
  1287. img = new Image();
  1288. //var svg = new Blob([data], {type: 'image/svg+xml;charset=utf-8'});
  1289. //var url = DOMURL.createObjectURL(svg);
  1290. //img.src = url;
  1291. img.src = 'data:image/svg+xml;base64,' + window.btoa(data);
  1292. cell.tag(img);
  1293. img.onload = function () {
  1294. context.sheet.repaint(new GC.Spread.Sheets.Rect(x, y, w, h));
  1295. }
  1296. };
  1297. return new HTMLCellType();
  1298. },
  1299. /**
  1300. * 获取 字符超长缩略的cellType
  1301. * @returns {EllipsisTextCellType}
  1302. */
  1303. getEllipsisTextCellType: function () {
  1304. const EllipsisTextCellType = function (){};
  1305. EllipsisTextCellType.prototype = new spreadNS.CellTypes.Text;
  1306. const proto = EllipsisTextCellType.prototype;
  1307. const getEllipsisText = function(c, str, maxWidth) {
  1308. var width = c.measureText(str).width;
  1309. var ellipsis = '…';
  1310. var ellipsisWidth = c.measureText(ellipsis).width;
  1311. if (width <= maxWidth || width <= ellipsisWidth) {
  1312. return str;
  1313. } else {
  1314. var len = str.length;
  1315. while (width >= maxWidth - ellipsisWidth && len-- > 0) {
  1316. str = str.substring(0, len);
  1317. width = c.measureText(str).width;
  1318. }
  1319. return str + ellipsis;
  1320. }
  1321. };
  1322. proto.paint = function (ctx, value, x, y, w, h, style, context) {
  1323. ctx.font = style.font;
  1324. value = getEllipsisText(ctx, value, w - 2);
  1325. spreadNS.CellTypes.Text.prototype.paint.apply(this, [ctx, value, x, y, w, h, style, context]);
  1326. };
  1327. return new EllipsisTextCellType();
  1328. },
  1329. /**
  1330. * 获取 动态显示ComboBox的cellType
  1331. * @returns {ActiveComboCellType}
  1332. */
  1333. getActiveComboCellType: function () {
  1334. const ActiveComboCellType = function () { };
  1335. ActiveComboCellType.prototype = new spreadNS.CellTypes.ComboBox();
  1336. const proto = ActiveComboCellType.prototype;
  1337. proto.paintValue = function (ctx, value, x, y, w, h, style, options) {
  1338. const sheet = options.sheet;
  1339. if (options.row === sheet.getActiveRowIndex() && options.col === sheet.getActiveColumnIndex()
  1340. && !sheet.getCell(options.row, options.col).locked()) {
  1341. spreadNS.CellTypes.ComboBox.prototype.paintValue.apply(this, arguments);
  1342. } else {
  1343. spreadNS.CellTypes.Base.prototype.paintValue.apply(this, arguments);
  1344. }
  1345. };
  1346. proto.getHitInfo = function (x, y, cellStyle, cellRect, options) {
  1347. const sheet = options.sheet;
  1348. if (options.row === sheet.getActiveRowIndex() && options.col === sheet.getActiveColumnIndex()
  1349. && !sheet.getCell(options.row, options.col).locked()) {
  1350. return spreadNS.CellTypes.ComboBox.prototype.getHitInfo.apply(this, [x, y, cellStyle, cellRect, options]);
  1351. } else {
  1352. return {
  1353. x: x,
  1354. y: y,
  1355. row: options.row,
  1356. col: options.col,
  1357. cellStyle: cellStyle,
  1358. cellRect: cellRect,
  1359. sheetArea: options.sheetArea
  1360. };
  1361. }
  1362. };
  1363. return new ActiveComboCellType();
  1364. },
  1365. /**
  1366. * 获取 单位的CellType
  1367. * @returns {GC.Spread.Sheets.CellTypes.ComboBox}
  1368. */
  1369. getUnitCellType: function () {
  1370. let combo = this.getActiveComboCellType();
  1371. combo.itemHeight(10).items(['m', 'km', 'm2', 'm3', 'dm3', 'kg', 't', 'm3·km',
  1372. '总额', '月' ,'项', '处' ,'个', '根', '棵', '块', '台', '系统', '每一试桩',
  1373. '桥长米', '公路公里', '株', '组', '座', '元', '工日', '套', '台班', '艘班', '亩',
  1374. 'm/处', 'm/道', 'm/座', 'm2/m', 'm3/m', 'm3/处', '根/米', 'm3/m2']);
  1375. return combo;
  1376. }
  1377. }
  1378. };