spreadjs_zh.js 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878
  1. /**
  2. * Spreadjs 通用方法集
  3. *
  4. * @author Mai
  5. * @date 2018/02/06
  6. * @version
  7. */
  8. // 定义画点线的方法
  9. const proto = window.CanvasRenderingContext2D && CanvasRenderingContext2D.prototype;
  10. proto.dottedLine = function (x1, y1, x2, y2, interval = 4) {
  11. const isHorizontal = x1 == x2 ? false : true;
  12. const dotLen = 1;
  13. let len = isHorizontal ? x2 - x1 : y2 - y1;
  14. this.moveTo(x1, y1);
  15. let progress = 0;
  16. while (len > progress) {
  17. if (progress > len) { progress = len; }
  18. if (isHorizontal) {
  19. this.moveTo(x1 + progress, y1);
  20. this.lineTo(x1 + progress + dotLen, y1);
  21. } else {
  22. this.moveTo(x1, y1 + progress);
  23. this.lineTo(x1, y1 + progress + dotLen);
  24. }
  25. progress += interval;
  26. }
  27. };
  28. // 简写Spread常量
  29. const spreadNS = GC.Spread.Sheets;
  30. // SpreadJs常用方法
  31. const SpreadJsObj = {
  32. DataType: {
  33. Data: 'data',
  34. Tree: 'tree',
  35. },
  36. /**
  37. * 创建Spread(默认1张表,3行数据)
  38. * @param obj 用于创建spreadjs的Dom元素
  39. * @returns {GC.Spread.Sheets.Workbook}
  40. */
  41. createNewSpread: function (obj) {
  42. const spread = new spreadNS.Workbook(obj, {sheetCount: 1});
  43. spread.options.tabStripVisible = false;
  44. spread.options.scrollbarMaxAlign = true;
  45. spread.options.cutCopyIndicatorVisible = false;
  46. spread.options.allowCopyPasteExcelStyle = false;
  47. spread.options.allowUserDragDrop = false;
  48. spread.options.allowUserEditFormula = false;
  49. spread.getActiveSheet().options.clipBoardOptions = GC.Spread.Sheets.ClipboardPasteOptions.values;//设置粘贴时只粘贴值
  50. spread.getActiveSheet().setRowCount(3);
  51. return spread;
  52. },
  53. /**
  54. * 保护sheet(需设置保护后, 单元格的locked等属性方可生效)
  55. * @param {GC.Spread.Sheets.Worksheet} sheet
  56. */
  57. protectedSheet: function (sheet) {
  58. const option = {
  59. allowSelectLockedCells: true,
  60. allowSelectUnlockedCells: true,
  61. allowResizeRows: true,
  62. allowResizeColumns: true
  63. };
  64. sheet.options.protectionOptions = option;
  65. sheet.options.isProtected = true;
  66. sheet.options.allowCellOverflow = false;
  67. },
  68. /**
  69. * sheet批量操作优化(sheet操作大批量数据时, 屏蔽数据刷新, 可优化大量时间)
  70. * @param {GC.Spread.Sheets.Worksheet} sheet
  71. * @param {function} operation
  72. */
  73. beginMassOperation: function (sheet) {
  74. sheet.suspendPaint();
  75. sheet.suspendEvent();
  76. },
  77. endMassOperation: function (sheet) {
  78. sheet.resumeEvent();
  79. sheet.resumePaint();
  80. },
  81. massOperationSheet: function (sheet, operation) {
  82. this.beginMassOperation(sheet);
  83. operation();
  84. this.endMassOperation(sheet);
  85. },
  86. /**
  87. * 获取Obj左顶点位置(部分功能需通过spreadjs左顶点位置计算)
  88. * @param obj
  89. * @returns {{x: number, y: number}}
  90. */
  91. getObjPos: function (obj) {
  92. let target = obj;
  93. let pos = {x: obj.offsetLeft, y: obj.offsetTop};
  94. target = obj.offsetParent;
  95. while (target) {
  96. pos.x += target.offsetLeft;
  97. pos.y += target.offsetTop;
  98. target = target.offsetParent;
  99. }
  100. return pos;
  101. },
  102. /**
  103. * 以下四个方法来自Spread示例, 参见官网或文档
  104. */
  105. getHitTest: function (obj, e, sheet) {
  106. var offset = obj.offset(),
  107. x = e.pageX - offset.left,
  108. y = e.pageY - offset.top;
  109. return sheet.hitTest(x, y);
  110. },
  111. getTargetSelection: function (sheet, target) {
  112. if (target.hitTestType === spreadNS.SheetArea.colHeader) {
  113. return sheet.getRange(-1, target.col, sheet.getRowCount(), 1);
  114. } else if (target.hitTestType === spreadNS.SheetArea.rowHeader) {
  115. return sheet.getRange(target.row, -1, 1, sheet.getColumnCount());
  116. } else if (target.hitTestType === spreadNS.SheetArea.viewport) {
  117. return sheet.getRange(target.row, target.col, 1, 1);
  118. } else if (target.hitTestType === spreadNS.SheetArea.corner) {
  119. return sheet.getRange(-1, -1, sheet.getRowCount(), sheet.getColumnCount());
  120. };
  121. },
  122. getCellInSelections: function (selections, row, col) {
  123. const count = selections.length;
  124. let range;
  125. for (var i = 0; i < count; i++) {
  126. range = selections[i];
  127. if (range.contains(row, col)) {
  128. return range;
  129. }
  130. }
  131. return null;
  132. },
  133. checkTargetInSelection: function (selections, range) {
  134. var count = selections.length, sel;
  135. for (var i = 0; i < count; i++) {
  136. sel = selections[i];
  137. if (sel.containsRange(range)) {
  138. return true;
  139. }
  140. }
  141. return false;
  142. },
  143. /**
  144. * 获取 spread 在鼠标右键时, spread的选中区域
  145. * viewport, 选中鼠标点击单元格X, X不在原选中区域内, 则选中X
  146. * colHeader, 选中整列
  147. * rowHeader, 选中整行
  148. * corner, 全选
  149. * 该方法返回不符合需求时,可通过getHitTest/getTargetSelection/getCellInSelections/checkTargetInSelection来确定鼠标右键点击时,spread当前Sheet应选中的单元格
  150. * @param obj: 创建Spread的Dom元素(jquery-contextmenu.build方法的第一个变量可读取)
  151. * @param e: jquery-contextmenu.build方法的第二个变量
  152. * @param {GC.Spread.Sheets.Workbook} spread
  153. * @returns {*}
  154. */
  155. safeRightClickSelection: function (obj, e, spread) {
  156. const sheet = spread.getActiveSheet();
  157. const selections = sheet.getSelections(), target = this.getHitTest(obj, e, sheet), range = this.getTargetSelection(sheet, target);
  158. if (!this.checkTargetInSelection(selections, range)) {
  159. sheet.setSelection(range.row, range.col, range.rowCount, range.colCount);
  160. }
  161. return target;
  162. },
  163. /**
  164. * sheet中 使用delete键,触发EndEdited事件
  165. * @param {GC.Spreads.Sheets.Workbook} spread
  166. * @param {function} fun
  167. */
  168. addDeleteBind: function (spread, fun) {
  169. spread.commandManager().register('deleteEvent', function () {
  170. fun(spread.getActiveSheet());
  171. });
  172. spread.commandManager().setShortcutKey(null, GC.Spread.Commands.Key.del, false, false, false, false);
  173. spread.commandManager().setShortcutKey('deleteEvent', GC.Spread.Commands.Key.del, false, false, false, false);
  174. },
  175. _initSheetDeafult: function (sheet) {
  176. if (sheet.zh_setting.headerFont) {
  177. const vStyle = new spreadNS.Style();
  178. vStyle.font = sheet.zh_setting.headerFont;
  179. sheet.setDefaultStyle(vStyle, spreadNS.SheetArea.colHeader);
  180. }
  181. if (sheet.zh_setting.font) {
  182. const vStyle = new spreadNS.Style();
  183. vStyle.font = sheet.zh_setting.font;
  184. sheet.setDefaultStyle(vStyle, spreadNS.SheetArea.viewport);
  185. }
  186. },
  187. /**
  188. * 根据sheet.zh_setting初始化sheet表头
  189. * @param {GC.Spread.Sheets.Worksheet} sheet
  190. */
  191. _initSheetHeader: function (sheet) {
  192. if (!sheet.zh_setting) { return; }
  193. sheet.setColumnCount(sheet.zh_setting.cols.length);
  194. sheet.setRowCount(sheet.zh_setting.headRows, spreadNS.SheetArea.colHeader);
  195. for (let iRow = 0; iRow < sheet.zh_setting.headRowHeight.length; iRow ++) {
  196. sheet.setRowHeight(iRow, sheet.zh_setting.headRowHeight[iRow], spreadNS.SheetArea.colHeader);
  197. }
  198. for (let iCol = 0; iCol < sheet.zh_setting.cols.length; iCol++) {
  199. const col = sheet.zh_setting.cols[iCol];
  200. const title = col.title.split('|');
  201. const colSpan = col.colSpan ? col.colSpan.split('|'): ['1'], rowSpan = col.rowSpan ? col.rowSpan.split('|'): ['1'];
  202. for (let i = 0; i < title.length; i++) {
  203. const cell = sheet.getCell(i, iCol, spreadNS.SheetArea.colHeader);
  204. cell.text(title[i]).wordWrap(true);
  205. if ((colSpan[i] !== '' && colSpan[i] !== '1') || (rowSpan[i] !== '' && rowSpan[i] !== '1')) {
  206. sheet.addSpan(i, iCol, parseInt(rowSpan[i]), parseInt(colSpan[i]), spreadNS.SheetArea.colHeader);
  207. }
  208. }
  209. sheet.setColumnWidth(iCol, col.width);
  210. if (col.visible !== undefined && col.visible !== null) {
  211. sheet.setColumnVisible(iCol, col.visible);
  212. }
  213. }
  214. sheet.rowOutlines.direction(spreadNS.Outlines.OutlineDirection.backward);
  215. sheet.showRowOutline(false);
  216. if (sheet.zh_setting.defaultRowHeight) {
  217. sheet.defaults.rowHeight = sheet.zh_setting.defaultRowHeight;
  218. }
  219. },
  220. /**
  221. * 初始化sheet, 设置sheet.zh_setting, 并初始化表头
  222. * @param {GC.Spread.Sheets.Worksheet} sheet
  223. * @param setting
  224. */
  225. initSheet: function (sheet, setting) {
  226. this.beginMassOperation(sheet);
  227. sheet.zh_setting = setting;
  228. this._initSheetDeafult(sheet);
  229. this._initSheetHeader(sheet);
  230. sheet.setRowCount(sheet.zh_setting.emptyRows);
  231. sheet.extendCellType = {};
  232. sheet.getRange(0, 0, sheet.getRowCount(), sheet.getColumnCount()).locked(setting.readOnly);
  233. this.endMassOperation(sheet);
  234. },
  235. _loadRowData: function (sheet, data, row) {
  236. // 单元格重新写入数据
  237. if (!data) { return }
  238. sheet.zh_setting.cols.forEach(function (col, j) {
  239. const cell = sheet.getCell(row, j);
  240. if (col.field !== '' && data[col.field]) {
  241. cell.value(data[col.field]);
  242. }
  243. if (col.readOnly && Object.prototype.toString.apply(col.readOnly) === "[object Function]") {
  244. cell.locked(col.readOnly(data) || sheet.zh_setting.readOnly || false).vAlign(1).hAlign(col.hAlign);
  245. } else {
  246. cell.locked(col.readOnly || sheet.zh_setting.readOnly || false).vAlign(1).hAlign(col.hAlign);
  247. }
  248. if (col.formatter) {
  249. cell.formatter(col.formatter);
  250. }
  251. });
  252. },
  253. /**
  254. * 整个sheet重新加载数据
  255. * @param {GC.Spread.Sheets.Worksheet} sheet
  256. */
  257. reLoadSheetData: function (sheet) {
  258. const self = this;
  259. const sortData = sheet.zh_dataType === 'tree' ? sheet.zh_tree.nodes : sheet.zh_data;
  260. this.beginMassOperation(sheet);
  261. try {
  262. sheet.clear(0, 0, sheet.getRowCount(), sheet.getColumnCount(), spreadNS.SheetArea.viewport, spreadNS.StorageType.data)
  263. // 设置总行数
  264. const totalRow = sortData.length + sheet.zh_setting.emptyRows;
  265. sheet.setRowCount(totalRow, spreadNS.SheetArea.viewport);
  266. // 控制空白行
  267. const emptyRows = sheet.getRange(sortData.length, -1, sheet.zh_setting.emptyRows, -1);
  268. emptyRows.locked(sheet.zh_dataType === 'tree');
  269. // 单元格写入数据
  270. sortData.forEach(function (data, i) {
  271. self._loadRowData(sheet, data, i);
  272. sheet.setRowVisible(i, data.visible);
  273. });
  274. // 设置列单元格格式
  275. sheet.zh_setting.cols.forEach(function (col, j) {
  276. //if (!col.cellType) { return; }
  277. if (col.cellType === 'tree') {
  278. if (!sheet.extendCellType.tree) {
  279. sheet.extendCellType.tree = self.CellType.getTreeNodeCellType();
  280. }
  281. sheet.getRange(-1, j, -1, 1).cellType(sheet.extendCellType.tree);
  282. } else if (col.cellType === 'tip') {
  283. if (!sheet.extendCellType.tip) {
  284. sheet.extendCellType.tip = self.CellType.getTipCellType();
  285. }
  286. sheet.getRange(-1, j, -1, 1).cellType(sheet.extendCellType.tip);
  287. } else if (col.cellType === 'checkbox') {
  288. if (!sheet.extendCellType.checkbox) {
  289. sheet.extendCellType.checkbox = new spreadNS.CellTypes.CheckBox();
  290. }
  291. sheet.getRange(-1, j, -1, 1).cellType(sheet.extendCellType.checkbox);
  292. }
  293. if (col.formatter) {
  294. sheet.getRange(-1, j, -1, 1).formatter(col.formatter);
  295. }
  296. });
  297. this.endMassOperation(sheet);
  298. } catch (err) {
  299. this.endMassOperation(sheet);
  300. }
  301. },
  302. /**
  303. * 重新加载部分数据行
  304. * @param {GC.Spread.Sheets.Worksheet} sheet
  305. * @param {Number} row
  306. * @param {Number} count
  307. */
  308. reLoadRowData: function (sheet, row, count = 1) {
  309. //if (row < 0) { return; }
  310. const self = this;
  311. const sortData = sheet.zh_dataType === 'tree' ? sheet.zh_tree.nodes : sheet.zh_data;
  312. this.beginMassOperation(sheet);
  313. try {
  314. // 清空原单元格数据
  315. sheet.clear(row, -1, count, -1, spreadNS.SheetArea.viewport, spreadNS.StorageType.data);
  316. // 单元格重新写入数据
  317. for (let i = row; i < row + count; i++) {
  318. const data = sortData[i];
  319. if (!data) { continue; }
  320. this._loadRowData(sheet, data, i);
  321. }
  322. this.endMassOperation(sheet);
  323. } catch (err) {
  324. this.endMassOperation(sheet);
  325. }
  326. },
  327. /**
  328. * 重新加载部分行数据
  329. * @param {GC.Spread.Sheets.Worksheet} sheet
  330. * @param {Array} rows
  331. */
  332. reLoadRowsData: function (sheet, rows) {
  333. const self = this;
  334. const sortData = sheet.zh_dataType === 'tree' ? sheet.zh_tree.nodes : sheet.zh_data;
  335. this.beginMassOperation(sheet);
  336. try {
  337. for (const row of rows) {
  338. if (row < 0) { continue; }
  339. // 清空原单元格数据
  340. sheet.clear(row, -1, 1, -1, spreadNS.SheetArea.viewport, spreadNS.StorageType.data);
  341. const data = sortData[row];
  342. // 单元格重新写入数据
  343. this._loadRowData(sheet, data, row);
  344. };
  345. this.endMassOperation(sheet);
  346. } catch (err) {
  347. this.endMassOperation(sheet);
  348. }
  349. },
  350. /**
  351. * 重新加载部分列数据
  352. * @param {GC.Spread.Sheets.Worksheet} sheet
  353. * @param {Array} cols
  354. */
  355. reLoadColsData: function (sheet, cols) {
  356. const self = this;
  357. const sortData = sheet.zh_dataType === 'tree' ? sheet.zh_tree.nodes : sheet.zh_data;
  358. this.beginMassOperation(sheet);
  359. try {
  360. for (const iCol of cols) {
  361. // 清空原单元格数据
  362. sheet.clear(-1, iCol, -1, 1, spreadNS.SheetArea.viewport, spreadNS.StorageType.data);
  363. const col = sheet.zh_setting.cols[iCol];
  364. sortData.forEach(function (data, i) {
  365. // 设置值
  366. const cell = sheet.getCell(i, iCol);
  367. if (col.field !== '' && data[col.field]) {
  368. cell.value(data[col.field]).locked(col.readOnly || sheet.zh_setting.readOnly || false).vAlign(1).hAlign(col.hAlign);
  369. } else {
  370. cell.locked(col.readOnly || sheet.zh_setting.readOnly || false).vAlign(1).hAlign(col.hAlign);
  371. }
  372. // 设置单元格格式
  373. if (col.formatter) {
  374. cell.formatter(col.formatter);
  375. }
  376. });
  377. }
  378. this.endMassOperation(sheet);
  379. } catch (err) {
  380. this.endMassOperation(sheet);
  381. }
  382. },
  383. reLoadNodesData: function (sheet, nodes) {
  384. this.beginMassOperation(sheet);
  385. nodes = nodes instanceof Array ? nodes : [nodes];
  386. for (const node of nodes) {
  387. const sortData = sheet.zh_dataType === 'tree' ? sheet.zh_tree.nodes : sheet.zh_data;
  388. this._loadRowData(sheet, node, sortData.indexOf(node));
  389. }
  390. this.endMassOperation(sheet);
  391. },
  392. /**
  393. * 根据data加载sheet数据,合并了一般数据和树结构数据的加载
  394. * @param {GC.Spread.Sheets.Worksheet} sheet
  395. * @param {String} dataType - 1.'zh_data' 2.'zh_tree'
  396. * @param {Array|PathTree} data - 对dataType对应
  397. */
  398. loadSheetData: function (sheet, dataType, data){
  399. sheet.zh_dataType = dataType;
  400. if (dataType === 'tree') {
  401. sheet.zh_tree = data;
  402. } else {
  403. sheet.zh_data = data;
  404. }
  405. this.protectedSheet(sheet);
  406. this.reLoadSheetData(sheet);
  407. },
  408. /**
  409. * 获取复制数据HTML格式(过滤不可见单元格)
  410. * @param {GC.Spread.Sheets.Worksheet} sheet
  411. * @returns {string}
  412. */
  413. getFilterCopyHTML: function (sheet) {
  414. const sel = sheet.getSelections()[0];
  415. const html = [];
  416. html.push('<table>');
  417. for (let i = sel.row, iLen = sel.row + sel.rowCount; i < iLen; i++) {
  418. // 跳过隐藏行
  419. if (!sheet.getCell(i, -1).visible()) { continue; }
  420. const rowHtml = [];
  421. rowHtml.push('<tr>');
  422. for (let j = sel.col, jLen = sel.col + sel.colCount; j < jLen; j++) {
  423. const data = sheet.getText(i, j);
  424. rowHtml.push('<td>' + data + '</td>');
  425. }
  426. rowHtml.push('</tr>');
  427. html.push(rowHtml.join(''));
  428. }
  429. html.push('</table>');
  430. return html.join('');
  431. },
  432. /**
  433. * 获取复制数据Text格式(过滤不可见单元格)
  434. * @param {GC.Spread.Sheets.Worksheet} sheet
  435. * @returns {string}
  436. */
  437. getFilterCopyText: function (sheet) {
  438. const copyData = [];
  439. const sel = sheet.getSelections()[0];
  440. for(let i = sel.row, iLen = sel.row + sel.rowCount; i < iLen; i++) {
  441. // 跳过隐藏行
  442. if (!sheet.getCell(i, -1).visible()) { continue; }
  443. const rowText = [];
  444. for (let j = sel.col, jLen = sel.col + sel.colCount; j < jLen; j++) {
  445. const data = sheet.getText(i, j);
  446. rowText.push(data);
  447. }
  448. copyData.push(rowText.join('\t'));
  449. }
  450. return copyData.join('\n');
  451. },
  452. /**
  453. * 树表结构,定位至指定的节点
  454. * @param {GC.Spread.Sheets.Worksheet} sheet - 需要定位的sheet
  455. * @param {Number} id - 定位节点的id
  456. */
  457. locateTreeNode: function (sheet, id) {
  458. const tree = sheet.zh_tree;
  459. if (!tree) { return }
  460. const node = tree.getItems(id);
  461. if (!node) { return }
  462. const index = tree.nodes.indexOf(node);
  463. const sels = sheet.getSelections();
  464. sheet.setSelection(index, sels[0].col, 1, 1);
  465. sheet.showRow(index, spreadNS.VerticalPosition.center);
  466. },
  467. /**
  468. * 获取当前选行的数据对象
  469. * @param {GC.Spread.Sheets.Worksheet} sheet
  470. * @returns {Object}
  471. */
  472. getSelectObject: function (sheet) {
  473. if (!sheet) {
  474. return null;
  475. } else if (sheet.zh_dataType) {
  476. const sel = sheet.getSelections()[0];
  477. if (sheet.zh_dataType === this.DataType.Tree) {
  478. return sheet.zh_tree.nodes[sel.row];
  479. } else if (sheet.zh_dataType === this.DataType.Data) {
  480. return sheet.zh_data[sel.row];
  481. } else {
  482. return null;
  483. }
  484. }
  485. },
  486. /**
  487. * 刷新列显示
  488. * @param sheet
  489. */
  490. refreshColumnVisible: function (sheet) {
  491. if(sheet.zh_setting) {
  492. sheet.zh_setting.cols.forEach(function (col, index) {
  493. if (col.visible !== undefined && col.visible !== null) {
  494. sheet.setColumnVisible(index, col.visible);
  495. }
  496. });
  497. }
  498. },
  499. /**
  500. * 刷新行显示
  501. * @param sheet
  502. */
  503. refreshTreeRowVisible: function (sheet) {
  504. this.beginMassOperation(sheet);
  505. if (sheet.zh_tree) {
  506. for (const iRow in sheet.zh_tree.nodes) {
  507. const node = sheet.zh_tree.nodes[iRow];
  508. if (node.visible !== undefined && node.visible !== null) {
  509. sheet.setRowVisible(iRow, node.visible);
  510. } else {
  511. sheet.setRowVisible(iRow, true);
  512. }
  513. }
  514. }
  515. this.endMassOperation(sheet);
  516. },
  517. /**
  518. * 刷新列是否只读
  519. * @param sheet
  520. * @param field
  521. * @param readonly
  522. */
  523. resetFieldReadOnly: function (sheet, field, readonly) {
  524. const fields = field instanceof Array ? field : [field];
  525. if (sheet.zh_setting) {
  526. sheet.zh_setting.cols.forEach(function (col, i) {
  527. if (fields.indexOf(col.field) !== -1) {
  528. col.readOnly = readonly;
  529. sheet.getRange(-1, i, -1, 1).locked(col.readOnly || sheet.zh_setting.readOnly || false);
  530. }
  531. });
  532. }
  533. },
  534. CellType: {
  535. /**
  536. * 获取树结构CellType
  537. * 通过SpreadJsObj.loadSheetData(sheet, 'tree', tree)加载树结构数据
  538. * 要求tree类型为PathTree, 节点必须含有{id, pid, level, order, is_leaf}数据
  539. * @returns {TreeNodeCellType}
  540. */
  541. getTreeNodeCellType: function () {
  542. const indent = 20;
  543. const levelIndent = -5;
  544. const halfBoxLength = 5;
  545. const halfExpandLength = 3;
  546. /**
  547. * 画一条点线段
  548. * @param canvas - 画布
  549. * @param x1 - 线段起点 x
  550. * @param y1 - 线段起点 y
  551. * @param x2 - 线段终点 x
  552. * @param y2 - 线段终点 y
  553. * @param color - 线段颜色
  554. */
  555. const drawDotLine = function (canvas, x1, y1, x2, y2, color) {
  556. canvas.save();
  557. // 设置偏移量
  558. canvas.translate(0.5, 0.5);
  559. canvas.beginPath();
  560. canvas.strokeStyle = color;
  561. canvas.dottedLine(x1, y1, x2, y2);
  562. canvas.stroke();
  563. canvas.restore();
  564. };
  565. /**
  566. * 画一条线段
  567. * @param canvas - 画布
  568. * @param x1 - 线段起点 x
  569. * @param y1 - 线段起点 y
  570. * @param x2 - 线段终点 x
  571. * @param y2 - 线段终点 y
  572. * @param color - 线段颜色
  573. */
  574. const drawLine = function (canvas, x1, y1, x2, y2, color) {
  575. canvas.save();
  576. // 设置偏移量
  577. canvas.translate(0.5, 0.5);
  578. canvas.beginPath();
  579. canvas.moveTo(x1, y1);
  580. canvas.lineTo(x2, y2);
  581. canvas.strokeStyle = color;
  582. canvas.stroke();
  583. canvas.restore();
  584. };
  585. /**
  586. * 画一个方框
  587. * @param {Object} canvas - 画布
  588. * @param {Object} rect - 方框区域
  589. * @param {String} lineColor - 画线颜色
  590. * @param {String} fillColor - 填充颜色
  591. */
  592. const drawBox = function (canvas, rect, lineColor, fillColor) {
  593. canvas.save();
  594. // 设置偏移量
  595. canvas.translate(0.5, 0.5);
  596. canvas.strokeStyle = lineColor;
  597. canvas.beginPath();
  598. canvas.moveTo(rect.left, rect.top);
  599. canvas.lineTo(rect.left, rect.bottom);
  600. canvas.lineTo(rect.right, rect.bottom);
  601. canvas.lineTo(rect.right, rect.top);
  602. canvas.lineTo(rect.left, rect.top);
  603. canvas.stroke();
  604. canvas.fillStyle = fillColor;
  605. canvas.fill();
  606. canvas.restore();
  607. };
  608. /**
  609. * 画树结构-展开收起按钮
  610. * @param {Object} canvas - 画布
  611. * @param {Number} x - 单元格左顶点坐标 x
  612. * @param {Number} y - 单元格左顶点坐标 y
  613. * @param {Number} w - 单元格宽度
  614. * @param {Number} h - 单元格高度
  615. * @param {Number} centerX - 按钮中央坐标
  616. * @param {Number} centerY - 按钮中央坐标
  617. * @param {Boolean} expanded - 当前节点展开收起状态
  618. */
  619. const drawExpandBox = function (canvas, x, y, w, h, centerX, centerY, expanded) {
  620. let rect = {
  621. top: centerY - halfBoxLength,
  622. bottom: centerY + halfBoxLength,
  623. left: centerX - halfBoxLength,
  624. right: centerX + halfBoxLength
  625. };
  626. let h1, h2, offset = 1;
  627. if (rect.left < x + w) {
  628. // 方框超出单元格宽度时,超出部分不画。
  629. rect.right = Math.min(rect.right, x + w);
  630. drawBox(canvas, rect, '#808080', 'white');
  631. // 画中心十字
  632. // 画十字横线
  633. h1 = centerX - halfExpandLength;
  634. h2 = Math.min(centerX + halfExpandLength, x + w);
  635. if (h2 > h1) {
  636. drawLine(canvas, h1, centerY, h2, centerY, '#808080');
  637. }
  638. // 画十字竖线
  639. if (!expanded && (centerX < x + w)) {
  640. drawLine(canvas, centerX, centerY - halfExpandLength, centerX, centerY + halfExpandLength, '#808080');
  641. }
  642. }
  643. };
  644. let TreeNodeCellType = function (){};
  645. TreeNodeCellType.prototype = new spreadNS.CellTypes.Text();
  646. const proto = TreeNodeCellType.prototype;
  647. /**
  648. * 绘制方法
  649. * @param {Object} canvas - 画布
  650. * @param value - cell.value
  651. * @param {Number} x - 单元格左顶点坐标 x
  652. * @param {Number} y - 单元格左顶点坐标 y
  653. * @param {Number} w - 单元格宽度
  654. * @param {Number} h - 单元格高度
  655. * @param {Object} style - cell.style
  656. * @param {Object} options
  657. */
  658. proto.paint = function (canvas, value, x, y, w, h, style, options) {
  659. // 清理 画布--单元格范围 旧数据
  660. if (style.backColor) {
  661. canvas.save();
  662. canvas.fillStyle = style.backColor;
  663. canvas.fillRect(x, y, w, h);
  664. canvas.restore();
  665. } else {
  666. canvas.clearRect(x, y, w, h);
  667. }
  668. const tree = options.sheet.zh_tree;
  669. // 使用TreeCellType前,需定义sheet.tree
  670. if (tree) {
  671. const node = options.row < tree.nodes.length ? tree.nodes[options.row] : null;
  672. if (node) {
  673. const showTreeLine = true;
  674. const centerX = Math.floor(x) + (node.level) * indent + (node.level) * levelIndent + indent / 2;
  675. const centerY = Math.floor((y + (y + h)) / 2);
  676. // Draw Sibling Line
  677. if (showTreeLine) {
  678. // Draw Horizontal Line
  679. if (centerX < x + w) {
  680. const x1 = centerX + indent / 2;
  681. //drawLine(canvas, centerX, centerY, Math.min(x1, x + w), centerY, 'gray');
  682. drawDotLine(canvas, centerX, centerY, Math.min(x1, x + w), centerY, '#b8b8b8');
  683. }
  684. // Draw Vertical Line
  685. if (centerX < x + w) {
  686. const y1 = tree.isLastSibling(node) ? centerY : y + h;
  687. const parent = tree.getParent(node);
  688. const y2 = y1 - centerY;
  689. if (node.order === 1 && !parent) {
  690. //drawLine(canvas, centerX, centerY, centerX, y1, 'gray');
  691. drawDotLine(canvas, centerX, centerY, centerX, y1, '#b8b8b8');
  692. } else {
  693. //drawLine(canvas, centerX, y, centerX, y1, 'gray');
  694. drawDotLine(canvas, centerX, y, centerX, y1, '#b8b8b8');
  695. }
  696. }
  697. }
  698. // Draw Expand Box
  699. if (!node.is_leaf) {
  700. drawExpandBox(canvas, x, y, w, h, centerX, centerY, node.expanded);
  701. }
  702. // Draw Parent Line
  703. if (showTreeLine) {
  704. let parent = tree.getParent(node), parentCenterX = centerX - indent - levelIndent;
  705. while (parent) {
  706. if (!tree.isLastSibling(parent)) {
  707. if (parentCenterX < x + w) {
  708. //drawLine(canvas, parentCenterX, y, parentCenterX, y + h, 'gray');
  709. drawDotLine(canvas, parentCenterX, y, parentCenterX, y + h, '#b8b8b8');
  710. }
  711. }
  712. parent = tree.getParent(parent);
  713. parentCenterX -= (indent + levelIndent);
  714. }
  715. };
  716. // 重定位x
  717. const move = (node.level + 1) * indent + (node.level) * levelIndent;
  718. x = x + move;
  719. w = w - move;
  720. }
  721. }
  722. // Drawing Text
  723. spreadNS.CellTypes.Text.prototype.paint.apply(this, [canvas, value, x, y, w, h, style, options]);
  724. };
  725. /**
  726. * 获取点击信息
  727. * @param {Number} x
  728. * @param {Number} y
  729. * @param {Object} cellStyle
  730. * @param {Object} cellRect
  731. * @param {Object} context
  732. * @returns {{x: *, y: *, row: *, col: *|boolean|*[]|number|{}|UE.dom.dtd.col, cellStyle: *, cellRect: *, sheet: *|StyleSheet, sheetArea: *}}
  733. */
  734. proto.getHitInfo = function (x, y, cellStyle, cellRect, context) {
  735. return {
  736. x: x,
  737. y: y,
  738. row: context.row,
  739. col: context.col,
  740. cellStyle: cellStyle,
  741. cellRect: cellRect,
  742. sheet: context.sheet,
  743. sheetArea: context.sheetArea
  744. };
  745. };
  746. /**
  747. * 鼠标点击 树结构按钮 响应展开收起(未加载子节点时,先加载子节点)
  748. * @param {Object} hitinfo - 见getHitInfo
  749. */
  750. proto.processMouseDown = function (hitinfo) {
  751. const offset = -1;
  752. const tree = hitinfo.sheet.zh_tree;
  753. if (!tree) { return; }
  754. const node = tree.nodes[hitinfo.row];
  755. if (!node) { return; }
  756. let centerX = hitinfo.cellRect.x + offset + (node.level) * indent + (node.level) * levelIndent + indent / 2;
  757. let centerY = (hitinfo.cellRect.y + offset + (hitinfo.cellRect.y + offset + hitinfo.cellRect.height)) / 2;
  758. // 点击展开节点时,如果已加载子项,则展开,反之这加载子项,展开
  759. if (Math.abs(hitinfo.x - centerX) < halfBoxLength && Math.abs(hitinfo.y - centerY) < halfBoxLength) {
  760. const children = tree.getChildren(node);
  761. if (!node.expanded && !node.is_leaf && children.length === 0 && tree.loadChildren) {
  762. tree.loadChildren(node, function () {
  763. node.expanded = true;
  764. const children = tree.getChildren(node);
  765. hitinfo.sheet.addRows(hitinfo.row + 1, children.length);
  766. SpreadJsObj.reLoadRowData(hitinfo.sheet, hitinfo.row + 1, children.length);
  767. });
  768. } else {
  769. tree.setExpanded(node, !node.expanded);
  770. SpreadJsObj.massOperationSheet(hitinfo.sheet, function () {
  771. const posterity = tree.getPosterity(node);
  772. for (const child of posterity) {
  773. hitinfo.sheet.setRowVisible(tree.nodes.indexOf(child), child.visible, hitinfo.sheetArea);
  774. }
  775. });
  776. hitinfo.sheet.repaint();
  777. }
  778. }
  779. };
  780. return new TreeNodeCellType();
  781. },
  782. /**
  783. * 获取带悬浮提示CellType
  784. * @returns {TipCellType}
  785. */
  786. getTipCellType: function () {
  787. const TipCellType = function () {};
  788. // 继承 SpreadJs定义的 普通的TextCellType
  789. TipCellType.prototype = new spreadNS.CellTypes.Text();
  790. const proto = TipCellType.prototype;
  791. /**
  792. * 获取点击信息
  793. * @param {Number} x
  794. * @param {Number} y
  795. * @param {Object} cellStyle
  796. * @param {Object} cellRect
  797. * @param {Object} context
  798. * @returns {{x: *, y: *, row: *, col: *|boolean|*[]|number|{}|UE.dom.dtd.col, cellStyle: *, cellRect: *, sheet: *|StyleSheet, sheetArea: *}}
  799. */
  800. proto.getHitInfo = function (x, y, cellStyle, cellRect, context) {
  801. return {
  802. x: x,
  803. y: y,
  804. row: context.row,
  805. col: context.col,
  806. cellStyle: cellStyle,
  807. cellRect: cellRect,
  808. sheet: context.sheet,
  809. sheetArea: context.sheetArea
  810. };
  811. };
  812. /**
  813. * 鼠标进入单元格事件 - 显示悬浮提示
  814. * @param {Object} hitinfo - 见getHitInfo返回值
  815. */
  816. proto.processMouseEnter = function (hitinfo) {
  817. const text = hitinfo.sheet.getText(hitinfo.row, hitinfo.col);
  818. const setting = hitinfo.sheet.setting;
  819. if (setting.pos && text && text !== '') {
  820. if (!this._toolTipElement) {
  821. let div = $('#autoTip')[0];
  822. if (!div) {
  823. div = document.createElement("div");
  824. $(div).css("position", "absolute")
  825. .css("border", "1px #C0C0C0 solid")
  826. .css("box-shadow", "1px 2px 5px rgba(0,0,0,0.4)")
  827. .css("font", "9pt Arial")
  828. .css("background", "white")
  829. .css("padding", 5)
  830. .attr("id", 'autoTip');
  831. $(div).hide();
  832. document.body.insertBefore(div, null);
  833. }
  834. this._toolTipElement = div;
  835. $(this._toolTipElement).text(text).css("top", setting.pos.y + hitinfo.y + 15).css("left", setting.pos.x + hitinfo.x + 15);
  836. $(this._toolTipElement).show("fast");
  837. }
  838. }
  839. };
  840. /**
  841. * 鼠标移出单元格事件 - 隐藏悬浮提示
  842. * @param {Object} hitinfo - 见getHitInfo返回值
  843. */
  844. proto.processMouseLeave = function (hitinfo) {
  845. if (this._toolTipElement) {
  846. $(this._toolTipElement).hide();
  847. this._toolTipElement = null;
  848. }
  849. };
  850. return new TipCellType();
  851. }
  852. }
  853. };