Hi,
I am having an existing excel file that needs to be insert or update cell formula.
The excel contains 7 Tab/Spreadsheet only in sheet1 I need to insert formula '=SUM(C1:C5)' The data is exists from A1 to C5.
I need to insert formula in C6. I have declared the C column as Decimal. The formula needs to be inserted in C6 so that when user changes the total it will dynamically update in C6.
I am using OpenXml.
Please help me with this problem. Thanks.
string file = @"E:\Test.xlsx";
byte[] bytes = File.ReadAllBytes(file);
MemoryStream ms = new MemoryStream();
ms.Write(bytes, 0, bytes.Length);
Attachment excelFile = MailManager.CreateAttachment(fileName, MediaTypeNames.Application.Octet, bData);
attachments.Add(excelFile);
using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(ms, true))
{
WorkbookPart workBookPart = spreadsheetDocument.WorkbookPart;
WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart;
WorksheetPart worksheetPart = workbookPart.WorksheetParts.First();
SheetData sheetData = worksheetPart.Worksheet.Elements<SheetData>().First();
//spreadsheetDocument.WorkbookPart.Workbook.Save();
//find the first row in the sheet data
Row row1 = sheetData.GetFirstChild<Row>();
//create a new cell
Cell cell = new Cell() { CellReference = "D18" };
CellFormula cellformula = new CellFormula();
cellformula.Text = "=SUM(D5:D15)";
cell.Append(cellformula);
//append the cell to the row
row1.Append(cell);
workbookPart.Workbook.Save();
spreadsheetDocument.Close();
File.WriteAllBytes(file, ms.ToArray());
}