Aspose.Cells像Microsoft Excel一样支持各种计算公式,开发人员可以快速为单元格设置各种计算公式,如果当Excel文件中存在公式时,客户想要查找替换其中的一些公式,也可以使用
Aspose.Cells提供的API进行公式的查找和替换,下面的代码讲述了如何在一个现存的Excel工作表中查找和替换计算公式,具体如下:
var source = new Workbook(dir + "book2.xlsx");
var sheet = source.Worksheets[0];
FindOptions opts = new FindOptions();
opts.LookInType = LookInType.OnlyFormulas;
opts.LookAtType = LookAtType.Contains;
string value = string.Empty;
Cell cell = null;
do
{
cell = sheet.Cells.Find("SUM", cell, opts);
if (cell != null && cell.IsFormula)
{
value = cell.Formula;
string svalue = value.Replace("SUM", "AVERAGE");
if (cell.IsInArray)
{
cell.SetArrayFormula(svalue,1, 1);
}
else
{
cell.Formula = svalue;
}
}
} while (cell != null);
source.CalculateFormula();
source.Save(dir + "output.xlsx", SaveFormat.Xlsx);