spreadjs_zh.js 68 KB

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