Click here to Skip to main content
15,890,512 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
my requirement to is to insert formula for a cell. i am using below method to insert formula. And its inserting formula corectly and formula working fine. but when i insert formula my excel file got corrpted and showing the message "Excel found unreadable content in "exceltemplate.xlsx". Do you want to recover the contents of..........". I searched lot,but not getting resolved. Please help to resolve this..
C#
public void InsertFormula(string filepath, string SheetName, string strCellIndex, string strFormula)
{
    using (SpreadsheetDocument document = SpreadsheetDocument.Open(filepath, true))
    {
        IEnumerable<Sheet> sheets = document.WorkbookPart.Workbook.Descendants<Sheet>().Where(s => s.Name == SheetName);
        if (sheets.Count() == 0)
        {
            // The specified worksheet does not exist.
            return;
        }
        WorksheetPart worksheetPart = (WorksheetPart)document.WorkbookPart.GetPartById(sheets.First().Id);
        Worksheet worksheet = worksheetPart.Worksheet;
        SheetData sheetData = worksheet.GetFirstChild<SheetData>();

        Row row1 = new Row()
        {
            RowIndex = (UInt32Value)4U,
            Spans = new ListValue<StringValue>()
        };

        Cell cell = new Cell() { CellReference = strCellIndex };
        CellFormula cellformula = new CellFormula();
        cellformula.Text = strFormula;
        cell.DataType = CellValues.Number;
        CellValue cellValue = new CellValue();
        cellValue.Text = "0";
        cell.Append(cellformula);
        cell.Append(cellValue);
        row1.Append(cell);

        sheetData.Append(row1);
        worksheet.Save();
        document.Close();
    }
}



And i am calling that method like below

SQL
InsertFormula(filepath, SheetName, "D15","=SUM(D9:D11)");
InsertFormula(filepath, SheetName, "D16", "=IF(D15-D6<0,0,D15-D6)");
Posted
Updated 13-May-13 20:10pm
v4
Comments
Maciej Los 13-May-13 15:02pm    
How can we help you, if you haven't wrote formula that occurs error?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900