我发现如果多个选区合并会弹多个窗,现在我考虑使用重写【MergeCells】、【MergeCenter】、【MergeAcross】方法来实现我的逻辑,正向功能实现了,但是当ctrl+z回退时,发现相当于只执行了取消合并的操作,单元格的状态无法恢复,代码如下:
- export function rewriteMergeCell(commandName){
- let newCommand=GC.Spread.Sheets.Designer.getCommand(commandName)
- let oldExecute = newCommand.execute
- newCommand.execute = function (context, options = {}, isMerge) {
- console.log(context, options, isMerge)
- if(!isMerge) {
- return oldExecute.call(this, context, options, isMerge)
- }
- const sheet= context.Spread.getActiveSheet()
- const selections=sheet.getSelections()
- const ranges = []
- function doSpan() {
- // GC.Spread.Sheets.Command.startTransaction(context.Spread, options)
- for (const range of ranges) {
- const {row, rowCount, col, colCount, firstFormula, firstValue} = range
- sheet.clear(row, col, rowCount, colCount, GC.Spread.Sheets.SheetArea.viewport,GC.Spread.Sheets.StorageType.data)
- if(firstFormula) {
- sheet.setFormula(row, col, firstFormula)
- } else {
- sheet.setValue(row, col, firstValue)
- }
- }
- oldExecute.call(this, context, options, isMerge)
- // GC.Spread.Sheets.Command.endTransaction(context.Spread, options)
- }
- for(const range of selections) {
- const { row, col, rowCount, colCount } = range
- // 保持和Excel行为一致,禁止表格区域合并
- for(const table of sheet.tables.all()) {
- if(isOverlapWithTable({ row, col, rowCount, colCount}, table)) {
- GC.Spread.Sheets.Designer.showMessageBox('禁止表格内的单元格合并', 'SpreadJS 设计器', GC.Spread.Sheets.Designer.MessageBoxIcon.warning)
- return
- }
- }
- // 保持和Excel行为一致
- // 合并前:[空][公式1][公式2] 合并后:[公式1],取消合并后:[公式1][空][空]
- // 合并前:[值1][公式1][公式2] 合并后:[值1],取消合并后:[值1][空][空]
- let firstFormula = null
- let firstValue = null
- let firstFind = false
- let valueCellCount = 0 // 有值的单元格个数
- for(let rowIndex = row; rowIndex <= row + rowCount - 1; rowIndex++) {
- for(let colIndex = col; colIndex <= col + colCount - 1; colIndex++) {
- const formula = sheet.getFormula(rowIndex, colIndex)
- const value = sheet.getValue(rowIndex, colIndex)
- if(!firstFind) {
- if(formula) {
- firstFormula = formula
- firstFind = true
- } else if(value !== null && value !== undefined) {
- firstValue = value
- firstFind = true
- }
- }
- if(formula || value) {
- valueCellCount++
- }
- }
- }
- ranges.push({row, rowCount, col, colCount, firstFormula, firstValue, valueCellCount, firstFind})
- }
- // 查询每个选区域,看看是否有的选区范围内有多个值
- let valueCellCount = 0
- for(const range of ranges) {
- valueCellCount = Math.max(range.valueCellCount, valueCellCount)
- }
- if(valueCellCount > 1) {
- GC.Spread.Sheets.Designer.showMessageBox(
- '合并单元格时,仅保留左上角的值,而放弃其他值。',
- 'SpreadJS 设计器',
- GC.Spread.Sheets.Designer.MessageBoxIcon.warning,
- (action) => {
- if(action === GC.Spread.Sheets.Designer.MessageBoxResult.ok) {
- doSpan()
- }
- },
- () => {},
- GC.Spread.Sheets.Designer.MessageBoxButtons.okCancel
- )
- } else {
- doSpan()
- }
- }
- return newCommand
- }
复制代码 |