spreadjs_zh.js 65 KB

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