I have a problem in C# when i try to generate new excel file with 4 values. When i try to open file i receive an error telling me : excel cannot open the file because the file format or file extension is not valid
When i try to debug it i have noticed that output is trowing : System invalid operation exception and i don't know how to fix this. i just want to generate excel file that has some values inside (later i will fill insert my values). For now i am just trying to create excel file that isn't corrupted.
[HttpPost]
public HttpResponseMessage PrintDevices()
{
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
using (MemoryStream output = new MemoryStream())
{
using (SpreadsheetDocument document = SpreadsheetDocument.Create(output, SpreadsheetDocumentType.Workbook))
{
WorkbookPart workbookPart = document.AddWorkbookPart();
workbookPart.Workbook = new Workbook();
WorksheetPart worksheetPart = workbookPart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet();
Sheets sheets = workbookPart.Workbook.AppendChild(new Sheets());
Sheet sheet = new Sheet()
{
Id = workbookPart.GetIdOfPart(worksheetPart),
SheetId = 1,
Name = "Testing"
};
sheets.Append(sheet);
workbookPart.Workbook.Save();
SheetData sheetData = worksheetPart.Worksheet.AppendChild(new SheetData());
// Constructing header
Row row = new Row();
row.Append(
ConstructCell("Id", CellValues.String),
ConstructCell("Name", CellValues.String),
ConstructCell("Birth Date", CellValues.String),
ConstructCell("Salary", CellValues.String));
// Insert the header row to the Sheet Data
sheetData.AppendChild(row);
// Inserting each employee
worksheetPart.Worksheet.Save();
}
}
Cell ConstructCell(string value, CellValues dataType)
{
return new Cell()
{
CellValue = new CellValue(value),
DataType = new EnumValue<CellValues>(dataType)
};
}
return response;
}