Search code examples
c#excelexcel-formulaepplusepplus-4

Copy Formula To Multiple Cells Using EPPlus


I am using Epplus and am using it to input a formula into cells K1 and K2 and this code works great for that. However, I need to "drag" the formulas from K1 and K2 to the right until I reach the last column with data.

My current code is

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;

Solution

  • Another method of achieving your desired result is this

    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++;
        }
    }