spreadjs_zh.js 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418
  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. if (Object.prototype.toString.apply(col.foreColor) === "[object Function]") {
  295. cell.foreColor(col.foreColor(data, sheet.getDefaultStyle().foreColor));
  296. } else {
  297. cell.foreColor(col.foreColor);
  298. }
  299. }
  300. if (col.readOnly && Object.prototype.toString.apply(col.readOnly) === "[object Function]") {
  301. cell.locked(col.readOnly(data) || sheet.zh_setting.readOnly || false).vAlign(1).hAlign(col.hAlign);
  302. } else {
  303. cell.locked(col.readOnly || sheet.zh_setting.readOnly || false).vAlign(1).hAlign(col.hAlign);
  304. }
  305. if (col.formatter) {
  306. cell.formatter(col.formatter);
  307. }
  308. if (sheet.zh_setting.getColor && Object.prototype.toString.apply(sheet.zh_setting.getColor) === "[object Function]") {
  309. cell.backColor(sheet.zh_setting.getColor(data, col, sheet.getDefaultStyle().backColor));
  310. }
  311. });
  312. },
  313. _defineColCellType: function (sheet, col, colSetting) {
  314. if(colSetting.cellType === 'ellipsis') {
  315. if (!sheet.extendCellType.ellipsis) {
  316. sheet.extendCellType.ellipsis = this.CellType.getEllipsisTextCellType();
  317. }
  318. sheet.getRange(-1, col, -1, 1).cellType(sheet.extendCellType.ellipsis);
  319. }
  320. if(colSetting.cellType === 'html') {
  321. if (!sheet.extendCellType.html) {
  322. sheet.extendCellType.html = this.CellType.getHtmlCellType();
  323. }
  324. sheet.getRange(-1, col, -1, 1).cellType(sheet.extendCellType.html);
  325. }
  326. if (colSetting.cellType === 'image') {
  327. if (!sheet.extendCellType.image) {
  328. sheet.extendCellType.image = this.CellType.getImageCellType();
  329. }
  330. sheet.getRange(-1, col, -1, 1).cellType(sheet.extendCellType.image);
  331. }
  332. if (colSetting.cellType === 'imageBtn') {
  333. if (!sheet.extendCellType.image) {
  334. sheet.extendCellType.imageBtn = this.CellType.getImageButtonCellType();
  335. }
  336. sheet.getRange(-1, col, -1, 1).cellType(sheet.extendCellType.imageBtn);
  337. }
  338. if (colSetting.cellType === 'tree') {
  339. if (!sheet.extendCellType.tree) {
  340. sheet.extendCellType.tree = this.CellType.getTreeNodeCellType();
  341. }
  342. sheet.getRange(-1, col, -1, 1).cellType(sheet.extendCellType.tree);
  343. }
  344. if (colSetting.cellType === 'tip') {
  345. if (!sheet.extendCellType.tip) {
  346. sheet.extendCellType.tip = this.CellType.getTipCellType();
  347. }
  348. sheet.getRange(-1, col, -1, 1).cellType(sheet.extendCellType.tip);
  349. }
  350. if (colSetting.cellType === 'checkbox') {
  351. if (!sheet.extendCellType.checkbox) {
  352. sheet.extendCellType.checkbox = new spreadNS.CellTypes.CheckBox();
  353. }
  354. sheet.getRange(-1, col, -1, 1).cellType(sheet.extendCellType.checkbox);
  355. }
  356. if (colSetting.cellType === 'unit') {
  357. if (!sheet.extendCellType.unit) {
  358. sheet.extendCellType.unit = this.CellType.getUnitCellType();
  359. }
  360. sheet.getRange(-1, col, -1, 1).cellType(sheet.extendCellType.unit);
  361. }
  362. if (colSetting.formatter) {
  363. sheet.getRange(-1, col, -1, 1).formatter(colSetting.formatter);
  364. }
  365. },
  366. /**
  367. * 整个sheet重新加载数据
  368. * @param {GC.Spread.Sheets.Worksheet} sheet
  369. */
  370. reLoadSheetData: function (sheet) {
  371. const self = this;
  372. const sortData = sheet.zh_dataType === 'tree' ? sheet.zh_tree.nodes : sheet.zh_data;
  373. this.beginMassOperation(sheet);
  374. try {
  375. sheet.clear(0, 0, sheet.getRowCount(), sheet.getColumnCount(), spreadNS.SheetArea.viewport, spreadNS.StorageType.data);
  376. // 设置总行数
  377. const totalRow = sortData.length + sheet.zh_setting.emptyRows;
  378. sheet.setRowCount(totalRow, spreadNS.SheetArea.viewport);
  379. // 控制空白行
  380. const emptyRows = sheet.getRange(sortData.length, -1, sheet.zh_setting.emptyRows, -1);
  381. emptyRows.locked(sheet.zh_dataType === 'tree');
  382. if (sortData) {
  383. // 单元格写入数据
  384. sortData.forEach(function (data, i) {
  385. self._loadRowData(sheet, data, i);
  386. sheet.setRowVisible(i, data.visible);
  387. });
  388. }
  389. // 设置列单元格格式
  390. sheet.zh_setting.cols.forEach(function (col, j) {
  391. //if (!col.cellType) { return; }
  392. self._defineColCellType(sheet, j, col);
  393. });
  394. this.endMassOperation(sheet);
  395. } catch (err) {
  396. this.endMassOperation(sheet);
  397. }
  398. },
  399. /**
  400. * 重新加载部分数据行
  401. * @param {GC.Spread.Sheets.Worksheet} sheet
  402. * @param {Number} row
  403. * @param {Number} count
  404. */
  405. reLoadRowData: function (sheet, row, count = 1) {
  406. //if (row < 0) { return; }
  407. const self = this;
  408. const sortData = sheet.zh_dataType === 'tree' ? sheet.zh_tree.nodes : sheet.zh_data;
  409. this.beginMassOperation(sheet);
  410. try {
  411. // 清空原单元格数据
  412. sheet.clear(row, -1, count, -1, spreadNS.SheetArea.viewport, spreadNS.StorageType.data);
  413. // 单元格重新写入数据
  414. for (let i = row; i < row + count; i++) {
  415. const data = sortData[i];
  416. if (!data) { continue; }
  417. this._loadRowData(sheet, data, i);
  418. }
  419. this.endMassOperation(sheet);
  420. } catch (err) {
  421. this.endMassOperation(sheet);
  422. }
  423. },
  424. /**
  425. * 重新加载部分行数据
  426. * @param {GC.Spread.Sheets.Worksheet} sheet
  427. * @param {Array} rows
  428. */
  429. reLoadRowsData: function (sheet, rows) {
  430. const self = this;
  431. const sortData = sheet.zh_dataType === 'tree' ? sheet.zh_tree.nodes : sheet.zh_data;
  432. this.beginMassOperation(sheet);
  433. try {
  434. for (const row of rows) {
  435. if (row < 0) { continue; }
  436. // 清空原单元格数据
  437. sheet.clear(row, -1, 1, -1, spreadNS.SheetArea.viewport, spreadNS.StorageType.data);
  438. const data = sortData[row];
  439. // 单元格重新写入数据
  440. this._loadRowData(sheet, data, row);
  441. };
  442. this.endMassOperation(sheet);
  443. } catch (err) {
  444. this.endMassOperation(sheet);
  445. }
  446. },
  447. /**
  448. * 重新加载部分列数据
  449. * @param {GC.Spread.Sheets.Worksheet} sheet
  450. * @param {Array} cols
  451. */
  452. reLoadColsData: function (sheet, cols) {
  453. const self = this;
  454. const sortData = sheet.zh_dataType === 'tree' ? sheet.zh_tree.nodes : sheet.zh_data;
  455. this.beginMassOperation(sheet);
  456. try {
  457. for (const iCol of cols) {
  458. // 清空原单元格数据
  459. sheet.clear(-1, iCol, -1, 1, spreadNS.SheetArea.viewport, spreadNS.StorageType.data);
  460. const col = sheet.zh_setting.cols[iCol];
  461. sortData.forEach(function (data, i) {
  462. // 设置值
  463. const cell = sheet.getCell(i, iCol);
  464. if (col.field !== '' && data[col.field]) {
  465. cell.value(data[col.field]).locked(col.readOnly || sheet.zh_setting.readOnly || false).vAlign(1).hAlign(col.hAlign);
  466. } else {
  467. cell.locked(col.readOnly || sheet.zh_setting.readOnly || false).vAlign(1).hAlign(col.hAlign);
  468. }
  469. // 设置单元格格式
  470. if (col.formatter) {
  471. cell.formatter(col.formatter);
  472. }
  473. });
  474. }
  475. this.endMassOperation(sheet);
  476. } catch (err) {
  477. this.endMassOperation(sheet);
  478. }
  479. },
  480. reLoadNodesData: function (sheet, nodes) {
  481. this.beginMassOperation(sheet);
  482. nodes = nodes instanceof Array ? nodes : [nodes];
  483. for (const node of nodes) {
  484. const sortData = sheet.zh_dataType === 'tree' ? sheet.zh_tree.nodes : sheet.zh_data;
  485. this._loadRowData(sheet, node, sortData.indexOf(node));
  486. }
  487. this.endMassOperation(sheet);
  488. },
  489. /**
  490. * 根据data加载sheet数据,合并了一般数据和树结构数据的加载
  491. * @param {GC.Spread.Sheets.Worksheet} sheet
  492. * @param {String} dataType - 1.'zh_data' 2.'zh_tree'
  493. * @param {Array|PathTree} data - 对dataType对应
  494. */
  495. loadSheetData: function (sheet, dataType, data){
  496. sheet.zh_dataType = dataType;
  497. if (dataType === 'tree') {
  498. sheet.zh_tree = data;
  499. } else {
  500. sheet.zh_data = data;
  501. }
  502. this.protectedSheet(sheet);
  503. this.reLoadSheetData(sheet);
  504. },
  505. /**
  506. * 获取复制数据HTML格式(过滤不可见单元格)
  507. * @param {GC.Spread.Sheets.Worksheet} sheet
  508. * @returns {string}
  509. */
  510. getFilterCopyHTML: function (sheet) {
  511. const sel = sheet.getSelections()[0];
  512. const html = [];
  513. html.push('<table>');
  514. for (let i = sel.row, iLen = sel.row + sel.rowCount; i < iLen; i++) {
  515. // 跳过隐藏行
  516. if (!sheet.getCell(i, -1).visible()) { continue; }
  517. const rowHtml = [];
  518. rowHtml.push('<tr>');
  519. for (let j = sel.col, jLen = sel.col + sel.colCount; j < jLen; j++) {
  520. const data = sheet.getText(i, j);
  521. rowHtml.push('<td>' + data + '</td>');
  522. }
  523. rowHtml.push('</tr>');
  524. html.push(rowHtml.join(''));
  525. }
  526. html.push('</table>');
  527. return html.join('');
  528. },
  529. /**
  530. * 获取复制数据Text格式(过滤不可见单元格)
  531. * @param {GC.Spread.Sheets.Worksheet} sheet
  532. * @returns {string}
  533. */
  534. getFilterCopyText: function (sheet) {
  535. const copyData = [];
  536. const sel = sheet.getSelections()[0];
  537. for(let i = sel.row, iLen = sel.row + sel.rowCount; i < iLen; i++) {
  538. // 跳过隐藏行
  539. if (!sheet.getCell(i, -1).visible()) { continue; }
  540. const rowText = [];
  541. for (let j = sel.col, jLen = sel.col + sel.colCount; j < jLen; j++) {
  542. const data = sheet.getText(i, j);
  543. rowText.push(data);
  544. }
  545. copyData.push(rowText.join('\t'));
  546. }
  547. return copyData.join('\n');
  548. },
  549. /**
  550. * 树表结构,定位至指定的节点
  551. * @param {GC.Spread.Sheets.Worksheet} sheet - 需要定位的sheet
  552. * @param {Number} id - 定位节点的id
  553. */
  554. locateTreeNode: function (sheet, id) {
  555. const tree = sheet.zh_tree;
  556. if (!tree) { return }
  557. const node = tree.getItems(id);
  558. if (!node) { return }
  559. const index = tree.nodes.indexOf(node);
  560. const sels = sheet.getSelections();
  561. sheet.setSelection(index, sels[0].col, 1, 1);
  562. sheet.showRow(index, spreadNS.VerticalPosition.center);
  563. },
  564. /**
  565. * 获取当前选行的数据对象
  566. * @param {GC.Spread.Sheets.Worksheet} sheet
  567. * @returns {Object}
  568. */
  569. getSelectObject: function (sheet) {
  570. if (!sheet) {
  571. return null;
  572. } else if (sheet.zh_dataType) {
  573. const sel = sheet.getSelections()[0];
  574. if (sheet.zh_dataType === this.DataType.Tree) {
  575. return sheet.zh_tree.nodes[sel.row];
  576. } else if (sheet.zh_dataType === this.DataType.Data) {
  577. return sheet.zh_data[sel.row];
  578. } else {
  579. return null;
  580. }
  581. }
  582. },
  583. /**
  584. * 刷新列显示
  585. * @param sheet
  586. */
  587. refreshColumnVisible: function (sheet) {
  588. if(sheet.zh_setting) {
  589. sheet.zh_setting.cols.forEach(function (col, index) {
  590. if (col.visible !== undefined && col.visible !== null) {
  591. sheet.setColumnVisible(index, col.visible);
  592. }
  593. });
  594. }
  595. },
  596. /**
  597. * 刷新行显示
  598. * @param sheet
  599. */
  600. refreshTreeRowVisible: function (sheet) {
  601. this.beginMassOperation(sheet);
  602. const sortData = sheet.zh_dataType === this.DataType.Data ? sheet.zh_data : sheet.zh_tree.nodes;
  603. for (const iRow in sortData) {
  604. const node = sortData[iRow];
  605. if (node.visible !== undefined && node.visible !== null) {
  606. sheet.setRowVisible(iRow, node.visible);
  607. } else {
  608. sheet.setRowVisible(iRow, true);
  609. }
  610. }
  611. // if (sheet.zh_tree) {
  612. // for (const iRow in sheet.zh_tree.nodes) {
  613. // const node = sheet.zh_tree.nodes[iRow];
  614. // if (node.visible !== undefined && node.visible !== null) {
  615. // sheet.setRowVisible(iRow, node.visible);
  616. // } else {
  617. // sheet.setRowVisible(iRow, true);
  618. // }
  619. // }
  620. // }
  621. this.endMassOperation(sheet);
  622. },
  623. refreshColumnAlign: function (sheet) {
  624. if (sheet.zh_setting) {
  625. for (const iCol in sheet.zh_setting.cols) {
  626. const col = sheet.zh_setting.cols[iCol];
  627. sheet.getRange(-1, iCol, -1, 1).hAlign(col.hAlign);
  628. }
  629. }
  630. },
  631. /**
  632. * 刷新列是否只读
  633. * @param sheet
  634. * @param field
  635. * @param readonly
  636. */
  637. resetFieldReadOnly: function (sheet, field, readonly) {
  638. const fields = field instanceof Array ? field : [field];
  639. if (sheet.zh_setting) {
  640. sheet.zh_setting.cols.forEach(function (col, i) {
  641. if (fields.indexOf(col.field) !== -1) {
  642. col.readOnly = readonly;
  643. sheet.getRange(-1, i, -1, 1).locked(col.readOnly || sheet.zh_setting.readOnly || false);
  644. }
  645. });
  646. }
  647. },
  648. CellType: {
  649. /**
  650. * 获取树结构CellType
  651. * 通过SpreadJsObj.loadSheetData(sheet, 'tree', tree)加载树结构数据
  652. * 要求tree类型为PathTree, 节点必须含有{id, pid, level, order, is_leaf}数据
  653. * @returns {TreeNodeCellType}
  654. */
  655. getTreeNodeCellType: function () {
  656. const indent = 20;
  657. const levelIndent = -5;
  658. const halfBoxLength = 5;
  659. const halfExpandLength = 3;
  660. /**
  661. * 画一条点线段
  662. * @param canvas - 画布
  663. * @param x1 - 线段起点 x
  664. * @param y1 - 线段起点 y
  665. * @param x2 - 线段终点 x
  666. * @param y2 - 线段终点 y
  667. * @param color - 线段颜色
  668. */
  669. const drawDotLine = function (canvas, x1, y1, x2, y2, color) {
  670. canvas.save();
  671. // 设置偏移量
  672. canvas.translate(0.5, 0.5);
  673. canvas.beginPath();
  674. canvas.strokeStyle = color;
  675. canvas.dottedLine(x1, y1, x2, y2);
  676. canvas.stroke();
  677. canvas.restore();
  678. };
  679. /**
  680. * 画一条线段
  681. * @param canvas - 画布
  682. * @param x1 - 线段起点 x
  683. * @param y1 - 线段起点 y
  684. * @param x2 - 线段终点 x
  685. * @param y2 - 线段终点 y
  686. * @param color - 线段颜色
  687. */
  688. const drawLine = function (canvas, x1, y1, x2, y2, color) {
  689. canvas.save();
  690. // 设置偏移量
  691. canvas.translate(0.5, 0.5);
  692. canvas.beginPath();
  693. canvas.moveTo(x1, y1);
  694. canvas.lineTo(x2, y2);
  695. canvas.strokeStyle = color;
  696. canvas.stroke();
  697. canvas.restore();
  698. };
  699. /**
  700. * 画一个方框
  701. * @param {Object} canvas - 画布
  702. * @param {Object} rect - 方框区域
  703. * @param {String} lineColor - 画线颜色
  704. * @param {String} fillColor - 填充颜色
  705. */
  706. const drawBox = function (canvas, rect, lineColor, fillColor) {
  707. canvas.save();
  708. // 设置偏移量
  709. canvas.translate(0.5, 0.5);
  710. canvas.strokeStyle = lineColor;
  711. canvas.beginPath();
  712. canvas.moveTo(rect.left, rect.top);
  713. canvas.lineTo(rect.left, rect.bottom);
  714. canvas.lineTo(rect.right, rect.bottom);
  715. canvas.lineTo(rect.right, rect.top);
  716. canvas.lineTo(rect.left, rect.top);
  717. canvas.stroke();
  718. canvas.fillStyle = fillColor;
  719. canvas.fill();
  720. canvas.restore();
  721. };
  722. /**
  723. * 画树结构-展开收起按钮
  724. * @param {Object} canvas - 画布
  725. * @param {Number} x - 单元格左顶点坐标 x
  726. * @param {Number} y - 单元格左顶点坐标 y
  727. * @param {Number} w - 单元格宽度
  728. * @param {Number} h - 单元格高度
  729. * @param {Number} centerX - 按钮中央坐标
  730. * @param {Number} centerY - 按钮中央坐标
  731. * @param {Boolean} expanded - 当前节点展开收起状态
  732. */
  733. const drawExpandBox = function (canvas, x, y, w, h, centerX, centerY, expanded) {
  734. let rect = {
  735. top: centerY - halfBoxLength,
  736. bottom: centerY + halfBoxLength,
  737. left: centerX - halfBoxLength,
  738. right: centerX + halfBoxLength
  739. };
  740. let h1, h2, offset = 1;
  741. if (rect.left < x + w) {
  742. // 方框超出单元格宽度时,超出部分不画。
  743. rect.right = Math.min(rect.right, x + w);
  744. drawBox(canvas, rect, '#808080', 'white');
  745. // 画中心十字
  746. // 画十字横线
  747. h1 = centerX - halfExpandLength;
  748. h2 = Math.min(centerX + halfExpandLength, x + w);
  749. if (h2 > h1) {
  750. drawLine(canvas, h1, centerY, h2, centerY, '#808080');
  751. }
  752. // 画十字竖线
  753. if (!expanded && (centerX < x + w)) {
  754. drawLine(canvas, centerX, centerY - halfExpandLength, centerX, centerY + halfExpandLength, '#808080');
  755. }
  756. }
  757. };
  758. let TreeNodeCellType = function (){};
  759. TreeNodeCellType.prototype = new spreadNS.CellTypes.Text();
  760. const proto = TreeNodeCellType.prototype;
  761. /**
  762. * 绘制方法
  763. * @param {Object} canvas - 画布
  764. * @param value - cell.value
  765. * @param {Number} x - 单元格左顶点坐标 x
  766. * @param {Number} y - 单元格左顶点坐标 y
  767. * @param {Number} w - 单元格宽度
  768. * @param {Number} h - 单元格高度
  769. * @param {Object} style - cell.style
  770. * @param {Object} options
  771. */
  772. proto.paint = function (canvas, value, x, y, w, h, style, options) {
  773. // 清理 画布--单元格范围 旧数据
  774. if (style.backColor) {
  775. canvas.save();
  776. canvas.fillStyle = style.backColor;
  777. canvas.fillRect(x, y, w, h);
  778. canvas.restore();
  779. } else {
  780. canvas.clearRect(x, y, w, h);
  781. }
  782. const tree = options.sheet.zh_tree;
  783. // 使用TreeCellType前,需定义sheet.tree
  784. if (tree) {
  785. const node = options.row < tree.nodes.length ? tree.nodes[options.row] : null;
  786. if (node) {
  787. const showTreeLine = true;
  788. const centerX = Math.floor(x) + (node.level) * indent + (node.level) * levelIndent + indent / 2;
  789. const centerY = Math.floor((y + (y + h)) / 2);
  790. // Draw Sibling Line
  791. if (showTreeLine) {
  792. // Draw Horizontal Line
  793. if (centerX < x + w) {
  794. const x1 = centerX + indent / 2;
  795. //drawLine(canvas, centerX, centerY, Math.min(x1, x + w), centerY, 'gray');
  796. drawDotLine(canvas, centerX, centerY, Math.min(x1, x + w), centerY, '#b8b8b8');
  797. }
  798. // Draw Vertical Line
  799. if (centerX < x + w) {
  800. const y1 = tree.isLastSibling(node) ? centerY : y + h;
  801. const parent = tree.getParent(node);
  802. const y2 = y1 - centerY;
  803. if (node.order === 1 && !parent) {
  804. //drawLine(canvas, centerX, centerY, centerX, y1, 'gray');
  805. drawDotLine(canvas, centerX, centerY, centerX, y1, '#b8b8b8');
  806. } else {
  807. //drawLine(canvas, centerX, y, centerX, y1, 'gray');
  808. drawDotLine(canvas, centerX, y, centerX, y1, '#b8b8b8');
  809. }
  810. }
  811. }
  812. // Draw Expand Box
  813. if (!node.is_leaf) {
  814. drawExpandBox(canvas, x, y, w, h, centerX, centerY, node.expanded);
  815. }
  816. // Draw Parent Line
  817. if (showTreeLine) {
  818. let parent = tree.getParent(node), parentCenterX = centerX - indent - levelIndent;
  819. while (parent) {
  820. if (!tree.isLastSibling(parent)) {
  821. if (parentCenterX < x + w) {
  822. //drawLine(canvas, parentCenterX, y, parentCenterX, y + h, 'gray');
  823. drawDotLine(canvas, parentCenterX, y, parentCenterX, y + h, '#b8b8b8');
  824. }
  825. }
  826. parent = tree.getParent(parent);
  827. parentCenterX -= (indent + levelIndent);
  828. }
  829. };
  830. // 重定位x
  831. const move = (node.level + 1) * indent + (node.level) * levelIndent;
  832. x = x + move;
  833. w = w - move;
  834. }
  835. }
  836. // Drawing Text
  837. spreadNS.CellTypes.Text.prototype.paint.apply(this, [canvas, value, x, y, w, h, style, options]);
  838. };
  839. /**
  840. * 获取点击信息
  841. * @param {Number} x
  842. * @param {Number} y
  843. * @param {Object} cellStyle
  844. * @param {Object} cellRect
  845. * @param {Object} context
  846. * @returns {{x: *, y: *, row: *, col: *|boolean|*[]|number|{}|UE.dom.dtd.col, cellStyle: *, cellRect: *, sheet: *|StyleSheet, sheetArea: *}}
  847. */
  848. proto.getHitInfo = function (x, y, cellStyle, cellRect, context) {
  849. return {
  850. x: x,
  851. y: y,
  852. row: context.row,
  853. col: context.col,
  854. cellStyle: cellStyle,
  855. cellRect: cellRect,
  856. sheet: context.sheet,
  857. sheetArea: context.sheetArea
  858. };
  859. };
  860. /**
  861. * 鼠标点击 树结构按钮 响应展开收起(未加载子节点时,先加载子节点)
  862. * @param {Object} hitinfo - 见getHitInfo
  863. */
  864. proto.processMouseDown = function (hitinfo) {
  865. const offset = -1;
  866. const tree = hitinfo.sheet.zh_tree;
  867. if (!tree) { return; }
  868. const node = tree.nodes[hitinfo.row];
  869. if (!node) { return; }
  870. let centerX = hitinfo.cellRect.x + offset + (node.level) * indent + (node.level) * levelIndent + indent / 2;
  871. let centerY = (hitinfo.cellRect.y + offset + (hitinfo.cellRect.y + offset + hitinfo.cellRect.height)) / 2;
  872. // 点击展开节点时,如果已加载子项,则展开,反之这加载子项,展开
  873. if (Math.abs(hitinfo.x - centerX) < halfBoxLength && Math.abs(hitinfo.y - centerY) < halfBoxLength) {
  874. const children = tree.getChildren(node);
  875. if (!node.expanded && !node.is_leaf && children.length === 0 && tree.loadChildren) {
  876. tree.loadChildren(node, function () {
  877. node.expanded = true;
  878. const children = tree.getChildren(node);
  879. hitinfo.sheet.addRows(hitinfo.row + 1, children.length);
  880. SpreadJsObj.reLoadRowData(hitinfo.sheet, hitinfo.row + 1, children.length);
  881. });
  882. } else {
  883. tree.setExpanded(node, !node.expanded);
  884. SpreadJsObj.massOperationSheet(hitinfo.sheet, function () {
  885. const posterity = tree.getPosterity(node);
  886. for (const child of posterity) {
  887. hitinfo.sheet.setRowVisible(tree.nodes.indexOf(child), child.visible, hitinfo.sheetArea);
  888. }
  889. });
  890. hitinfo.sheet.repaint();
  891. }
  892. }
  893. };
  894. return new TreeNodeCellType();
  895. },
  896. /**
  897. * 获取 带悬浮提示的CellType
  898. * @returns {TipCellType}
  899. */
  900. getTipCellType: function () {
  901. const TipCellType = function () {};
  902. // 继承 SpreadJs定义的 普通的TextCellType
  903. TipCellType.prototype = new spreadNS.CellTypes.Text();
  904. const proto = TipCellType.prototype;
  905. /**
  906. * 获取点击信息
  907. * @param {Number} x
  908. * @param {Number} y
  909. * @param {Object} cellStyle
  910. * @param {Object} cellRect
  911. * @param {Object} context
  912. * @returns {{x: *, y: *, row: *, col: *|boolean|*[]|number|{}|UE.dom.dtd.col, cellStyle: *, cellRect: *, sheet: *|StyleSheet, sheetArea: *}}
  913. */
  914. proto.getHitInfo = function (x, y, cellStyle, cellRect, context) {
  915. return {
  916. x: x,
  917. y: y,
  918. row: context.row,
  919. col: context.col,
  920. cellStyle: cellStyle,
  921. cellRect: cellRect,
  922. sheet: context.sheet,
  923. sheetArea: context.sheetArea
  924. };
  925. };
  926. /**
  927. * 鼠标进入单元格事件 - 显示悬浮提示
  928. * @param {Object} hitinfo - 见getHitInfo返回值
  929. */
  930. proto.processMouseEnter = function (hitinfo) {
  931. const text = hitinfo.sheet.getText(hitinfo.row, hitinfo.col);
  932. const setting = hitinfo.sheet.setting;
  933. if (setting.pos && text && text !== '') {
  934. if (!this._toolTipElement) {
  935. let div = $('#autoTip')[0];
  936. if (!div) {
  937. div = document.createElement("div");
  938. $(div).css("position", "absolute")
  939. .css("border", "1px #C0C0C0 solid")
  940. .css("box-shadow", "1px 2px 5px rgba(0,0,0,0.4)")
  941. .css("font", "9pt Arial")
  942. .css("background", "white")
  943. .css("padding", 5)
  944. .attr("id", 'autoTip');
  945. $(div).hide();
  946. document.body.insertBefore(div, null);
  947. }
  948. this._toolTipElement = div;
  949. $(this._toolTipElement).text(text).css("top", setting.pos.y + hitinfo.y + 15).css("left", setting.pos.x + hitinfo.x + 15);
  950. $(this._toolTipElement).show("fast");
  951. }
  952. }
  953. };
  954. /**
  955. * 鼠标移出单元格事件 - 隐藏悬浮提示
  956. * @param {Object} hitinfo - 见getHitInfo返回值
  957. */
  958. proto.processMouseLeave = function (hitinfo) {
  959. if (this._toolTipElement) {
  960. $(this._toolTipElement).hide();
  961. this._toolTipElement = null;
  962. }
  963. };
  964. return new TipCellType();
  965. },
  966. /**
  967. * 获取 带图片的cellType(图片需在document中定义好img,并写入col的img属性)
  968. *
  969. * img:
  970. * 1. 整列固定,则传入img的select
  971. * e.g. {title: '附件', field: 'attachment', cellType: 'image', img = '#attachment-img'}
  972. *
  973. * 2. 各单元格自定义,则
  974. * e.g. {title: '附件', field: 'attachment', cellType: 'image', img = getAttachmentImage}
  975. * function getAttachmentImage (data) {
  976. * $('#attachment-img').url = data.attachmentImageUrl;
  977. * return $('#attachment-img')[0];
  978. * }
  979. *
  980. * @returns {ImageCellType}
  981. */
  982. getImageCellType: function () {
  983. const ImageCellType = function (){};
  984. ImageCellType.prototype = new spreadNS.CellTypes.Text();
  985. const proto = ImageCellType.prototype;
  986. proto.getImage = function (sheet, iRow, iCol) {
  987. const col = sheet.zh_setting.cols[iCol];
  988. let imgSource = col.img;
  989. if (imgSource && Object.prototype.toString.apply(imgSource) === "[object Function]") {
  990. const sortData = SpreadJsObj.getSortData(sheet);
  991. const data = sortData ? sortData[iRow] : null;
  992. return data ? imgSource(data) : null;
  993. } else {
  994. return $(imgSource)[0] ? $(imgSource)[0] : null;
  995. }
  996. };
  997. proto.paint = function (canvas, value, x, y, w, h, style, options) {
  998. const col = options.sheet.zh_setting.cols[options.col];
  999. const img = this.getImage(options.sheet, options.row, options.col);
  1000. const indent = col.indent ? col.indent : 10;
  1001. if (img) {
  1002. if (style.backColor) {
  1003. canvas.save();
  1004. canvas.fillStyle = style.backColor;
  1005. canvas.fillRect(x, y, indent + img.width, h);
  1006. canvas.restore();
  1007. }
  1008. canvas.drawImage(img, x + indent, y + (h - img.height) / 2);
  1009. if (style.hAlign !== spreadNS.HorizontalAlign.left) {
  1010. style.hAlign = spreadNS.HorizontalAlign.left;
  1011. }
  1012. x = x + indent + img.width;
  1013. w = w - indent - img.width;
  1014. }
  1015. // Drawing Text
  1016. spreadNS.CellTypes.Text.prototype.paint.apply(this, [canvas, value, x, y, w, h, style, options]);
  1017. };
  1018. /**
  1019. * 获取点击信息
  1020. * @param {Number} x
  1021. * @param {Number} y
  1022. * @param {Object} cellStyle
  1023. * @param {Object} cellRect
  1024. * @param {Object} context
  1025. * @returns {{x: *, y: *, row: *, col: *|boolean|*[]|number|{}|UE.dom.dtd.col, cellStyle: *, cellRect: *, sheet: *|StyleSheet, sheetArea: *}}
  1026. */
  1027. proto.getHitInfo = function (x, y, cellStyle, cellRect, context) {
  1028. return {
  1029. x: x,
  1030. y: y,
  1031. row: context.row,
  1032. col: context.col,
  1033. cellStyle: cellStyle,
  1034. cellRect: cellRect,
  1035. sheet: context.sheet,
  1036. sheetArea: context.sheetArea
  1037. };
  1038. };
  1039. /**
  1040. * 鼠标点击
  1041. * @param {Object} hitinfo - 见getHitInfo
  1042. */
  1043. proto.processMouseDown = function (hitinfo) {
  1044. const img = this.getImage(hitinfo.sheet, hitinfo.row, hitinfo.col);
  1045. if (img) {
  1046. const halfX = img.width / 2, halfY = img.height / 2;
  1047. const centerX = hitinfo.cellRect.x + indent + halfX;
  1048. const centerY = hitinfo.cellRect.y + hitinfo.cellRect.height / 2;
  1049. // 点击展开节点时,如果已加载子项,则展开,反之这加载子项,展开
  1050. if (Math.abs(hitinfo.x - centerX) < halfX && Math.abs(hitinfo.y - centerY) < halfY) {
  1051. const imageClick = hitinfo.sheet.zh_setting ? hitinfo.sheet.zh_setting.imageClick : null;
  1052. if (imageClick && Object.prototype.toString.apply(imageClick) === "[object Function]") {
  1053. const sortData = SpreadJsObj.getSortData(hitinfo.sheet);
  1054. const data = sortData ? sortData[hitinfo.row] : null;
  1055. imageClick(data);
  1056. }
  1057. }
  1058. }
  1059. };
  1060. return new ImageCellType();
  1061. },
  1062. /**
  1063. *
  1064. * 获取 带normal-hover-active按钮的cellType(需定义三张图片,须在document中定义好img,并写入col的normalImg, hoverImg, activeImg属性)
  1065. * 其中:normalImg必需,向下套用(不存在activeImg则使用hoverImg,不存在hoverImg则使用normalImg)
  1066. * 三个img均可像getImageCellType一样动态获取,参见getImageCellType注释
  1067. *
  1068. * @returns {ImageCellType}
  1069. */
  1070. getImageButtonCellType: function () {
  1071. let hover = 1, active = 2;
  1072. const ImageCellType = function (){};
  1073. ImageCellType.prototype = new spreadNS.CellTypes.Text();
  1074. const proto = ImageCellType.prototype;
  1075. proto.getImage = function (sheet, iRow, iCol) {
  1076. const col = sheet.zh_setting.cols[iCol];
  1077. let imgSource = col.normalImg;
  1078. const cell = sheet.getCell(iRow, iCol), tag = cell.tag();
  1079. if (tag === active) {
  1080. imgSource = col.activeImg ? col.activeImg : (col.hoverImg ? col.hoverImg : col.normalImg);
  1081. } else if (tag === hover) {
  1082. imgSource = col.hoverImg ? col.hoverImg : col.normalImg;
  1083. }
  1084. if (imgSource && Object.prototype.toString.apply(imgSource) === "[object Function]") {
  1085. const sortData = SpreadJsObj.getSortData(sheet);
  1086. const data = sortData ? sortData[iRow] : null;
  1087. return data ? imgSource(data) : null;
  1088. } else {
  1089. return $(imgSource)[0] ? $(imgSource)[0] : null;
  1090. }
  1091. };
  1092. proto.paint = function (canvas, value, x, y, w, h, style, options) {
  1093. const col = options.sheet.zh_setting.cols[options.col];
  1094. const sortData = SpreadJsObj.getSortData(options.sheet);
  1095. const data = sortData ? sortData[options.row] : null;
  1096. let showImage = true;
  1097. if (col.showImage && Object.prototype.toString.apply(col.showImage) === "[object Function]") {
  1098. showImage = col.showImage(data);
  1099. }
  1100. const img = showImage ? this.getImage(options.sheet, options.row, options.col) : null;
  1101. const indent = col.indent ? col.indent : 10;
  1102. if (style.hAlign === spreadNS.HorizontalAlign.right) {
  1103. if (img) {
  1104. if (style.backColor) {
  1105. canvas.save();
  1106. canvas.fillStyle = style.backColor;
  1107. canvas.fillRect(x + w - indent - img.width, y, img.width, h);
  1108. canvas.restore();
  1109. }
  1110. canvas.drawImage(img, x + w - indent - img.width, y + (h - img.height) / 2);
  1111. w = w - indent - img.width;
  1112. }
  1113. // Drawing Text
  1114. spreadNS.CellTypes.Text.prototype.paint.apply(this, [canvas, value, x, y, w, h, style, options]);
  1115. } else {
  1116. if (img) {
  1117. if (style.backColor) {
  1118. canvas.save();
  1119. canvas.fillStyle = style.backColor;
  1120. canvas.fillRect(x, y, indent + img.width, h);
  1121. canvas.restore();
  1122. }
  1123. canvas.drawImage(img, x + 10, y + (h - img.height) / 2);
  1124. if (style.hAlign !== spreadNS.HorizontalAlign.left) {
  1125. style.hAlign = spreadNS.HorizontalAlign.left;
  1126. }
  1127. x = x + indent + img.width;
  1128. w = w - indent - img.width;
  1129. }
  1130. // Drawing Text
  1131. spreadNS.CellTypes.Text.prototype.paint.apply(this, [canvas, value, x, y, w, h, style, options]);
  1132. }
  1133. };
  1134. /**
  1135. * 获取点击信息
  1136. * @param {Number} x
  1137. * @param {Number} y
  1138. * @param {Object} cellStyle
  1139. * @param {Object} cellRect
  1140. * @param {Object} context
  1141. * @returns {{x: *, y: *, row: *, col: *|boolean|*[]|number|{}|UE.dom.dtd.col, cellStyle: *, cellRect: *, sheet: *|StyleSheet, sheetArea: *}}
  1142. */
  1143. proto.getHitInfo = function (x, y, cellStyle, cellRect, context) {
  1144. return {
  1145. x: x,
  1146. y: y,
  1147. row: context.row,
  1148. col: context.col,
  1149. cellStyle: cellStyle,
  1150. cellRect: cellRect,
  1151. sheet: context.sheet,
  1152. sheetArea: context.sheetArea
  1153. };
  1154. };
  1155. /**
  1156. * 鼠标点击
  1157. * @param {Object} hitinfo - 见getHitInfo
  1158. */
  1159. proto.processMouseEnter = function (hitinfo) {
  1160. const col = hitinfo.sheet.zh_setting.cols[hitinfo.col];
  1161. // Drawing Image
  1162. if (col.hoverImg) {
  1163. const cell = hitinfo.sheet.getCell(hitinfo.row, hitinfo.col);
  1164. cell.tag(hover);
  1165. hitinfo.sheet.repaint(hitinfo.cellRect);
  1166. }
  1167. };
  1168. proto.processMouseLeave = function (hitinfo) {
  1169. const col = hitinfo.sheet.zh_setting.cols[hitinfo.col];
  1170. // Drawing Image
  1171. if (col.hoverImg) {
  1172. const cell = hitinfo.sheet.getCell(hitinfo.row, hitinfo.col);
  1173. cell.tag(null);
  1174. hitinfo.sheet.repaint(hitinfo.cellRect);
  1175. }
  1176. };
  1177. proto.processMouseDown = function (hitinfo) {
  1178. const col = hitinfo.sheet.zh_setting.cols[hitinfo.col];
  1179. if (col.activeImg) {
  1180. const cell = hitinfo.sheet.getCell(hitinfo.row, hitinfo.col);
  1181. cell.tag(active);
  1182. hitinfo.sheet.repaint(hitinfo.cellRect);
  1183. }
  1184. };
  1185. proto.processMouseUp = function (hitinfo) {
  1186. const col = hitinfo.sheet.zh_setting.cols[hitinfo.col];
  1187. const sortData = SpreadJsObj.getSortData(hitinfo.sheet);
  1188. const data = sortData ? sortData[hitinfo.row] : null;
  1189. if (col.showImage && Object.prototype.toString.apply(col.showImage) === "[object Function]") {
  1190. if (!col.showImage(data)) {
  1191. return;
  1192. }
  1193. }
  1194. const imageClick = hitinfo.sheet.zh_setting ? hitinfo.sheet.zh_setting.imageClick : null;
  1195. if (imageClick && Object.prototype.toString.apply(imageClick) === "[object Function]") {
  1196. imageClick(data);
  1197. const cell = hitinfo.sheet.getCell(hitinfo.row, hitinfo.col);
  1198. cell.tag(null);
  1199. hitinfo.sheet.repaint(hitinfo.cellRect);
  1200. }
  1201. };
  1202. /*
  1203. 注释部分以进入鼠标进入图片,点击图片为基准更新图片,鼠标快速移动时,可能失效
  1204. */
  1205. // proto.processMouseDown = function (hitinfo) {
  1206. // const img = this.getImage(hitinfo.sheet, hitinfo.row, hitinfo.col);
  1207. // const halfX = img.width / 2, halfY = img.height / 2;
  1208. // const centerX = hitinfo.cellRect.x + indent + halfX;
  1209. // const centerY = hitinfo.cellRect.y + hitinfo.cellRect.height / 2;
  1210. //
  1211. // if (Math.abs(hitinfo.x - centerX) < halfX && Math.abs(hitinfo.y - centerY) < halfY) {
  1212. // const cell = hitinfo.sheet.getCell(hitinfo.row, hitinfo.col);
  1213. // cell.tag(down);
  1214. // hitinfo.sheet.repaint(hitinfo.cellRect);
  1215. // }
  1216. // };
  1217. // proto.processMouseUp = function (hitinfo) {
  1218. // const img = this.getImage(hitinfo.sheet, hitinfo.row, hitinfo.col);
  1219. // const halfX = img.width / 2, halfY = img.height / 2;
  1220. // const centerX = hitinfo.cellRect.x + indent + halfX;
  1221. // const centerY = hitinfo.cellRect.y + hitinfo.cellRect.height / 2;
  1222. //
  1223. // // 点击展开节点时,如果已加载子项,则展开,反之这加载子项,展开
  1224. // if (Math.abs(hitinfo.x - centerX) < halfX && Math.abs(hitinfo.y - centerY) < halfY) {
  1225. // const imageClick = hitinfo.sheet.zh_setting ? hitinfo.sheet.zh_setting.imageClick : null;
  1226. // if (imageClick && Object.prototype.toString.apply(imageClick) === "[object Function]") {
  1227. // const sortData = SpreadJsObj.getSortData(hitinfo.sheet);
  1228. // const data = sortData ? sortData[hitinfo.row] : null;
  1229. // imageClick(data);
  1230. // const cell = hitinfo.sheet.getCell(hitinfo.row, hitinfo.col);
  1231. // cell.tag(null);
  1232. // hitinfo.sheet.repaint(hitinfo.cellRect);
  1233. // }
  1234. // }
  1235. // };
  1236. // proto.processMouseMove = function (hitinfo) {
  1237. // const img = this.getImage(hitinfo.sheet, hitinfo.row, hitinfo.col);
  1238. // const halfX = img.width / 2, halfY = img.height / 2;
  1239. // const centerX = hitinfo.cellRect.x + indent + halfX;
  1240. // const centerY = hitinfo.cellRect.y + hitinfo.cellRect.height / 2;
  1241. // const cell = hitinfo.sheet.getCell(hitinfo.row, hitinfo.col);
  1242. // if (Math.abs(hitinfo.x - centerX) < halfX && Math.abs(hitinfo.y - centerY) < halfY) {
  1243. // if (cell.tag() !== hover) {
  1244. // cell.tag(hover);
  1245. // hitinfo.sheet.repaint(hitinfo.cellRect);
  1246. // }
  1247. // } else {
  1248. // if (cell.tag() === hover) {
  1249. // cell.tag(null);
  1250. // hitinfo.sheet.repaint(hitinfo.cellRect);
  1251. // }
  1252. // }
  1253. // };
  1254. return new ImageCellType();
  1255. },
  1256. /**
  1257. * 获取 嵌入Html的cellType
  1258. * @returns {HTMLCellType}
  1259. */
  1260. getHtmlCellType: function () {
  1261. const HTMLCellType = function (){};
  1262. HTMLCellType.prototype = new spreadNS.CellTypes.Text;
  1263. const proto = ImageCellType.prototype;
  1264. proto.paint = function (ctx, value, x, y, w, h, style, context) {
  1265. let DOMURL = window.URL || window.webkitURL || window;
  1266. let cell = context.sheet.getCell(context.row, context.col);
  1267. let img = cell.tag();
  1268. if (img) {
  1269. try {
  1270. ctx.save();
  1271. ctx.rect(x, y, w, h);
  1272. ctx.clip();
  1273. ctx.drawImage(img, x + 2, y + 2)
  1274. ctx.restore();
  1275. cell.tag(null);
  1276. return;
  1277. }
  1278. catch (err) {
  1279. GC.Spread.Sheets.CustomCellType.prototype.paint.apply(this, [ctx, "#HTMLError", x, y, w, h, style, context])
  1280. cell.tag(null);
  1281. return;
  1282. }
  1283. }
  1284. let svgPattern = '<svg xmlns="http://www.w3.org/2000/svg" width="{0}" height="{1}">' +
  1285. '<foreignObject width="100%" height="100%"><div xmlns="http://www.w3.org/1999/xhtml" style="font:{2}">{3}</div></foreignObject></svg>';
  1286. let data = svgPattern.replace("{0}", w).replace("{1}", h).replace("{2}", style.font).replace("{3}", value);
  1287. let doc = document.implementation.createHTMLDocument("");
  1288. doc.write(data);
  1289. // Get well-formed markup
  1290. data = (new XMLSerializer()).serializeToString(doc.body.children[0]);
  1291. img = new Image();
  1292. //var svg = new Blob([data], {type: 'image/svg+xml;charset=utf-8'});
  1293. //var url = DOMURL.createObjectURL(svg);
  1294. //img.src = url;
  1295. img.src = 'data:image/svg+xml;base64,' + window.btoa(data);
  1296. cell.tag(img);
  1297. img.onload = function () {
  1298. context.sheet.repaint(new GC.Spread.Sheets.Rect(x, y, w, h));
  1299. }
  1300. };
  1301. return new HTMLCellType();
  1302. },
  1303. /**
  1304. * 获取 字符超长缩略的cellType
  1305. * @returns {EllipsisTextCellType}
  1306. */
  1307. getEllipsisTextCellType: function () {
  1308. const EllipsisTextCellType = function (){};
  1309. EllipsisTextCellType.prototype = new spreadNS.CellTypes.Text;
  1310. const proto = EllipsisTextCellType.prototype;
  1311. const getEllipsisText = function(c, str, maxWidth) {
  1312. var width = c.measureText(str).width;
  1313. var ellipsis = '…';
  1314. var ellipsisWidth = c.measureText(ellipsis).width;
  1315. if (width <= maxWidth || width <= ellipsisWidth) {
  1316. return str;
  1317. } else {
  1318. var len = str.length;
  1319. while (width >= maxWidth - ellipsisWidth && len-- > 0) {
  1320. str = str.substring(0, len);
  1321. width = c.measureText(str).width;
  1322. }
  1323. return str + ellipsis;
  1324. }
  1325. };
  1326. proto.paint = function (ctx, value, x, y, w, h, style, context) {
  1327. ctx.font = style.font;
  1328. value = getEllipsisText(ctx, value, w - 2);
  1329. spreadNS.CellTypes.Text.prototype.paint.apply(this, [ctx, value, x, y, w, h, style, context]);
  1330. };
  1331. return new EllipsisTextCellType();
  1332. },
  1333. /**
  1334. * 获取 动态显示ComboBox的cellType
  1335. * @returns {ActiveComboCellType}
  1336. */
  1337. getActiveComboCellType: function () {
  1338. const ActiveComboCellType = function () { };
  1339. ActiveComboCellType.prototype = new spreadNS.CellTypes.ComboBox();
  1340. const proto = ActiveComboCellType.prototype;
  1341. proto.paintValue = function (ctx, value, x, y, w, h, style, options) {
  1342. const sheet = options.sheet;
  1343. if (options.row === sheet.getActiveRowIndex() && options.col === sheet.getActiveColumnIndex()
  1344. && !sheet.getCell(options.row, options.col).locked()) {
  1345. spreadNS.CellTypes.ComboBox.prototype.paintValue.apply(this, arguments);
  1346. } else {
  1347. spreadNS.CellTypes.Base.prototype.paintValue.apply(this, arguments);
  1348. }
  1349. };
  1350. proto.getHitInfo = function (x, y, cellStyle, cellRect, options) {
  1351. const sheet = options.sheet;
  1352. if (options.row === sheet.getActiveRowIndex() && options.col === sheet.getActiveColumnIndex()
  1353. && !sheet.getCell(options.row, options.col).locked()) {
  1354. return spreadNS.CellTypes.ComboBox.prototype.getHitInfo.apply(this, [x, y, cellStyle, cellRect, options]);
  1355. } else {
  1356. return {
  1357. x: x,
  1358. y: y,
  1359. row: options.row,
  1360. col: options.col,
  1361. cellStyle: cellStyle,
  1362. cellRect: cellRect,
  1363. sheetArea: options.sheetArea
  1364. };
  1365. }
  1366. };
  1367. return new ActiveComboCellType();
  1368. },
  1369. /**
  1370. * 获取 单位的CellType
  1371. * @returns {GC.Spread.Sheets.CellTypes.ComboBox}
  1372. */
  1373. getUnitCellType: function () {
  1374. let combo = this.getActiveComboCellType();
  1375. combo.itemHeight(10).items(['m', 'km', 'm2', 'm3', 'dm3', 'kg', 't', 'm3·km',
  1376. '总额', '月' ,'项', '处' ,'个', '根', '棵', '块', '台', '系统', '每一试桩',
  1377. '桥长米', '公路公里', '株', '组', '座', '元', '工日', '套', '台班', '艘班', '亩',
  1378. 'm/处', 'm/道', 'm/座', 'm2/m', 'm3/m', 'm3/处', '根/米', 'm3/m2']);
  1379. return combo;
  1380. }
  1381. }
  1382. };