首页 文章

Excel Open xml sdk - 在具有范围修改的单元格之间复制公式

提问于
浏览
0

我有一个公式细胞(CellFormula) . 我不知道公式内容(可能是Sum,ifs或任何其他计算) .
公式可能包括范围 .
将单元格拖动到其他单元格(在Excel应用程序本身手动)时,公式范围将更新 .
我希望公式编程副本的行为方式相同 .
如果公式包含范围说明符,我想将它们更新为当前行 .
没有正则表达式操作,是否有一些内置的方法可以做到这一点?

1 回答

  • 1

    我不知道这是否是一个涵盖所有可能性的好解决方案,但......

    //Formula update
    if (cloneFromCell.CellFormula != null && (cloneFromCell.CellFormula.FormulaType == null || !cloneFromCell.CellFormula.FormulaType.HasValue || cloneFromCell.CellFormula.FormulaType.Value == CellFormulaValues.Normal))
    {
        uint cloneRowIndex = OXMLTools.GetRowIndex(cloneFromCell.CellReference);
        uint offset = rowIndex - cloneRowIndex;
        exCell.CellFormula.Text = OXMLTools.GetUpdatedFormulaToNewRow(cloneFromCell.CellFormula.Text, offset);
    }
    
    public static string GetUpdatedFormulaToNewRow(string formula, uint offset)
    {
        return Regex.Replace(formula, @"[A-Za-z]+\d+", delegate(Match match)
        {
          //Calculate the new row for this cell in the formula by the given offset
          uint oldRow = GetRowIndex(match.Value);
          string col = GetColumnName(match.Value);
          uint newRow = oldRow + offset;
    
          //Create the new reference for this cell
          string newRef = col + newRow;
          return newRef;
        });
     }
    

相关问题