spreadjs_zh.js 64 KB

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