使用EPPlus将公式复制到多个单元格

4

我正在使用Epplus,并使用它向单元格K1K2输入公式。这段代码对此非常有效。然而,我需要将公式从K1K2“拖动”到右侧,直到达到最后一个包含数据的列。

我的当前代码是:

ws.Cells["K1"].Formula = "=LEFT(K7,(FIND(\" \", K7,1))";
ws.Cells["K2"].Formula = "=RIGHT(K7,LEN(K7)-FIND(\" \", K&,1))";
ws.Cells["K2"].Style.WrapText = true;
ws.Cells["K2"].Style.VerticalAlignment = ExcelVerticalAlignment.Center;
ws.Cells["K2"].Style.HorizontalAlighment = ExcelHorizontalAlignment.Center;
2个回答

2
另一种实现您所需结果的方法如下:
using (var pck = new ExcelPackage(new FileInfo("C:\\Test\\Test.xlsx")))
{
    ExcelWorksheet ws = pck.Workbook.Worksheets[0];
    var startColumnIndex = 11;
    const int dataSourceRowIndex = 3; 

    while (ws.Cells[dataSourceRowIndex, startColumnIndex].Value != null)
    {
        ws.Cells[1, startColumnIndex].Formula = $"=LEFT({ws.Cells[dataSourceRowIndex, startColumnIndex].Address},(FIND(\" \",{ws.Cells[dataSourceRowIndex, startColumnIndex].Address},1)-1))";
        ws.Cells[2, startColumnIndex].Formula = $"=RIGHT({ws.Cells[dataSourceRowIndex, startColumnIndex].Address},LEN({ws.Cells[dataSourceRowIndex, startColumnIndex].Address})-FIND(\" \",{ws.Cells[dataSourceRowIndex, startColumnIndex].Address},1))";
        ws.Cells[2, startColumnIndex].Style.WrapText = true;
        ws.Cells[2, startColumnIndex].Style.VerticalAlignment = ExcelVerticalAlignment.Center;
        ws.Cells[2, startColumnIndex].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;

        startColumnIndex++;
    }
}

1

以下是如何操作。创建一个区域并添加一个公式,其中包含将在公式中使用的第一个单元格。下面是一个带有随机数据的简单工作示例。

Random rnd = new Random();

//create a new ExcelPackage
using (ExcelPackage excelPackage = new ExcelPackage())
{
    //create the WorkSheet
    ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets.Add("Sheet 1");

    //add 10 rows and 5 cols of dummy data
    for (int i = 1; i <= 10; i++)
    {
        for (int j = 1; j <= 5; j++)
        {
            worksheet.Cells[i, j].Value = rnd.Next(1, 1000);
        }
    }

    //get the range for the cells that will contain the formula
    //in this case column G, row 1 to the last row
    var range = worksheet.Cells[1, 7, worksheet.Dimension.End.Row, 7];

    //add the formula to the range
    //you can use the first row for the values, epplus will make the range working for the correct cells
    range.Formula = string.Format("SUM({0}:{1})", worksheet.Cells[1, 1].Address, worksheet.Cells[1, 5].Address);

    //calculate the formulas
    worksheet.Calculate();
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接