Abdul Hameed

Abdul Hameed

  • 1.8k
  • 41
  • 123

Writing to excel using Open XML

Mar 7 2019 11:46 PM
I have written a code to write to an excel file in OpenXML. this works for only one time for the second time, I am getting an error while opening the file as "We found a problem with some content in output.xlsx"
  1. public static void WriteToExcel(string fileName, string SKU_Address, string SKU_Value, string ItemName_Address, string Item_Name_Value)  
  2. {  
  3. SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(fileName, true);  
  4. // Add a WorkbookPart to the document.  
  5. WorkbookPart workbookpart = spreadsheetDocument.WorkbookPart;  
  6. // Add a WorksheetPart to the WorkbookPart.  
  7. WorksheetPart worksheetPart = workbookpart.WorksheetParts.FirstOrDefault();  
  8. Worksheet worksheet = worksheetPart.Worksheet;  
  9. SheetData sheetData = worksheetPart.Worksheet.Elements<SheetData>().First();  
  10. Row row = new Row();  
  11. //intialize a cell and add values to the required cell based on address  
  12. Cell cell1 = new Cell()  
  13. {  
  14. CellReference = SKU_Address,  
  15. DataType = CellValues.String,  
  16. CellValue = new CellValue(SKU_Value)  
  17. };  
  18. row.Append(cell1);  
  19. //intialize a cell and add values to the required cell based on address  
  20. Cell cell2 = new Cell()  
  21. {  
  22. CellReference = ItemName_Address,  
  23. DataType = CellValues.String,  
  24. CellValue = new CellValue(Item_Name_Value)  
  25. };  
  26. row.Append(cell2);  
  27. sheetData.Append(row);  
  28. worksheetPart.Worksheet.Save();  
  29. // Close the document.  
  30. spreadsheetDocument.Close();  
  31. }  
I guess I am missing something somewhere else. please help.

Answers (2)