spreadjs_zh.js 62 KB

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