Error message when opening excel file using openXml in .Net? - c#

I am trying to download the large excel file using open xml. I am able to download it. My excel file contains more than 100k records. When I double click on the file, I get below error message.
Below is my code.
public MemoryStream WriteExcelUsingOpenXML(IEnumerable<string> headers, IEnumerable<IEnumerable<string>> values, string worksheetName)
{
var stream = new MemoryStream();
var headersArray = headers.ToArray();
using (SpreadsheetDocument document = SpreadsheetDocument.Create(stream, 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 = Constants.TimephaseWorksheet };
sheets.Append(sheet);
workbookPart.Workbook.Save();
SheetData sheetData = worksheetPart.Worksheet.AppendChild(new SheetData());
// Constructing header
Row row = new Row();
foreach (var data in headersArray)
{
row.Append(ConstructCell(headersArray[0], CellValues.SharedString));
}
// Insert the header row to the Sheet Data
sheetData.AppendChild(row);
// Inserting each employee
foreach (var valuesEnumeration in values)
{
row = new Row();
var flattend = valuesEnumeration.ToArray();
row.Append(
ConstructCell(flattend[0], CellValues.Number),
ConstructCell(flattend[1], CellValues.SharedString),
ConstructCell(flattend[2], CellValues.SharedString),
ConstructCell(flattend[3], CellValues.Number),
ConstructCell(flattend[4], CellValues.SharedString));
sheetData.AppendChild(row);
}
worksheetPart.Worksheet.Save();
}
return stream;
}
private Cell ConstructCell(string value, CellValues dataType)
{
return new Cell()
{
CellValue = new CellValue(value),
DataType = new EnumValue<CellValues>(dataType)
};
}
Below is the sample data of excel file.
How to fix the error?

Related

Excel getting corrupt when created through Code C#

I was trying to create an excel using Memory Stream. Here is the code I'm trying,
using (MemoryStream mem = new MemoryStream())
{
using (var sheetDocument = SpreadsheetDocument.Create(mem, SpreadsheetDocumentType.Workbook))
{
//// Add a WorkbookPart to the document.
WorkbookPart workbookpart = sheetDocument.AddWorkbookPart();
workbookpart.Workbook = new Workbook();
WorkbookStylesPart workbookstyle = workbookpart.AddNewPart<WorkbookStylesPart>();
workbookstyle.Stylesheet = this.GenerateStyleSheet();
workbookstyle.Stylesheet.Save();
//// Add a WorksheetPart to the WorkbookPart.
WorksheetPart worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet();
Columns cols = new Columns();
Column col = new Column();
col.BestFit = true;
col.CustomWidth = true;
col.Width = 22.33;
col.Max = 13;
col.Min = 1;
cols.Append(col);
worksheetPart.Worksheet.Append(cols);
SheetData sheetData = new SheetData();
worksheetPart.Worksheet.Append(sheetData);
//// Add Sheets to the Workbook.
Sheets sheets = sheetDocument.WorkbookPart.Workbook.AppendChild<Sheets>(new Sheets());
//// Append a new worksheet and associate it with the workbook.
Sheet sheet = new Sheet() { Id = sheetDocument.WorkbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = sheetName };
sheets.Append(sheet);
workbookpart.Workbook.Save();
List<string> columns = new List<string>();
foreach (DataColumn column in table.Columns)
{
columns.Add(column.ColumnName);
}
DocumentFormat.OpenXml.Spreadsheet.Row headerRow = this.CreateHeaderRow(columns);
sheetData.AppendChild(headerRow);
foreach (DataRow dataSetRow in table.Rows)
{
DocumentFormat.OpenXml.Spreadsheet.Row newRow = this.CreateDataRow(dataSetRow);
sheetData.AppendChild(newRow);
}
workbookpart.Workbook.Save();
var result = mem.ToArray();
System.IO.File.WriteAllBytes(fileName, result);
}
An excel file is getting created, but when I try to open it, I'm getting an error as bellow
If I press yes, it says
The workbook cannot be opened or repaired by Microsoft Excel because
it is corrupt
How can I fix this?
Thanks to #zaikhan's comment, I was able to fix my issue. When I closed the sheetDocument it worked.
using (MemoryStream mem = new MemoryStream())
{
using (var sheetDocument = SpreadsheetDocument.Create(mem, SpreadsheetDocumentType.Workbook))
{
//// Add a WorkbookPart to the document.
WorkbookPart workbookpart = sheetDocument.AddWorkbookPart();
workbookpart.Workbook = new Workbook();
WorkbookStylesPart workbookstyle = workbookpart.AddNewPart<WorkbookStylesPart>();
workbookstyle.Stylesheet = this.GenerateStyleSheet();
workbookstyle.Stylesheet.Save();
//// Add a WorksheetPart to the WorkbookPart.
WorksheetPart worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet();
Columns cols = new Columns();
Column col = new Column();
col.BestFit = true;
col.CustomWidth = true;
col.Width = 22.33;
col.Max = 13;
col.Min = 1;
cols.Append(col);
worksheetPart.Worksheet.Append(cols);
SheetData sheetData = new SheetData();
worksheetPart.Worksheet.Append(sheetData);
//// Add Sheets to the Workbook.
Sheets sheets = sheetDocument.WorkbookPart.Workbook.AppendChild<Sheets>(new Sheets());
//// Append a new worksheet and associate it with the workbook.
Sheet sheet = new Sheet() { Id = sheetDocument.WorkbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = sheetName };
sheets.Append(sheet);
workbookpart.Workbook.Save();
List<string> columns = new List<string>();
foreach (DataColumn column in table.Columns)
{
columns.Add(column.ColumnName);
}
DocumentFormat.OpenXml.Spreadsheet.Row headerRow = this.CreateHeaderRow(columns);
sheetData.AppendChild(headerRow);
foreach (DataRow dataSetRow in table.Rows)
{
DocumentFormat.OpenXml.Spreadsheet.Row newRow = this.CreateDataRow(dataSetRow);
sheetData.AppendChild(newRow);
}
workbookpart.Workbook.Save();
sheetDocument.Close();
}
var result = mem.ToArray();
System.IO.File.WriteAllBytes(fileName, result);
}

filling an excel sheet with data asp.net mvc

I am writing a routine to create and fill an Excel sheet in ASP.NET MVC. The object that I want to transfer to the sheet is a List, where T is a structure.
Do you know of any piece of code that does this?
The constructor that do this is:
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
…
public byte[] ExcelContent;
public ExportExcel(List<OrdViewModel> ol)
{
MemoryStream memstream = new MemoryStream();
SpreadsheetDocument XlsxDoc = SpreadsheetDocument.Create(memstream, SpreadsheetDocumentType.Workbook);
WorkbookPart workbookpart = XlsxDoc.AddWorkbookPart();
workbookpart.Workbook = new Workbook();
// Add a WorksheetPart to the WorkbookPart.
WorksheetPart worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet(new SheetData());
// Add Sheets to the Workbook.
Sheets sheets = XlsxDoc.WorkbookPart.Workbook.
AppendChild<Sheets>(new Sheets());
Sheet sheet = new Sheet()
{
Id = XlsxDoc.WorkbookPart.GetIdOfPart(worksheetPart),
SheetId = 1,
Name = "Sheet1"
};
sheets.Append(sheet);
// code here…
XlsxDoc.Close();
ExcelContent = memstream.ToArray();
}
You can use my SwiftExcel library. It was designed to maximize performance and minimize memory usage when writing to Excel:
public ExportExcel(List<OrdViewModel> ol)
{
using (var ew = new ExcelWriter("C:\\temp\\test.xlsx"))
{
for (var row = 1; row <= ol.Count; row++)
{
var item = ol[row-1];
ew.Write(item.YourProperty1, 1, row);
ew.Write(item.YourProperty2, 2, row);
ew.Write(item.YourProperty3, 3, row);
ew.Write(item.YourProperty4, 4, row);
}
}
}

Error in generating excel

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

Open XML: How to add rows and cell value after appending new sheet in existing Excel file using c#

I inserted/appended new sheet in existing Excel file using open XML but I am not able to add rows and cell values. Following is my code:
using (var workbook = SpreadsheetDocument.Open(excelFilePath, true))
{
var workbookPart = workbook.WorkbookPart;
var wb = workbookPart.Workbook;
int rowIndex = 0;
// Add a blank WorksheetPart.
WorksheetPart newWorksheetPart = workbook.WorkbookPart.AddNewPart<WorksheetPart>();
newWorksheetPart.Worksheet = new Worksheet(new SheetData());
Sheets sheets = workbook.WorkbookPart.Workbook.GetFirstChild<Sheets>();
string relationshipId = workbook.WorkbookPart.GetIdOfPart(newWorksheetPart);
// Get a unique ID for the new worksheet.
uint sheetId = 1;
if (sheets.Elements<Sheet>().Count() > 0)
{
sheetId = sheets.Elements<Sheet>().Select(s => s.SheetId.Value).Max() + 1;
}
// Give the new worksheet a name.
string sheetName = "Data";
// Append the new worksheet and associate it with the workbook.
Sheet dataSheet = new Sheet() { Id = relationshipId, SheetId = sheetId, Name = sheetName };
sheets.Append(sheet);
workbookPart.Workbook.Save();
var sharedStringPart = workbookPart.SharedStringTablePart;
var values = sharedStringPart.SharedStringTable.Elements<SharedStringItem>().ToArray();
Row headerRow = new Row();
Cell cell = new Cell();
cell.DataType = CellValues.String;
cell.CellValue = new CellValue("EmpId");
headerRow.AppendChild<Cell>(cell);
cell = new Cell();
cell.DataType = CellValues.String;
cell.CellValue = new CellValue("Name");
headerRow.AppendChild<Cell>(cell);
headerRow.AppendChild<Cell>(cell);
dataSheet.InsertAt<Row>(headerRow, rowIndex++);
workbookPart.Workbook.Save();
}
}
It's throwing an exception:
Non-composite elements do not have child elements.
When i got this error ("Non-composite elements do not have child elements.") was about my sheet object. I got the worng object to Apeend, so you need change the use .Append to something like that:
Worksheet worksheet = worksheetPart.Worksheet;
SheetData sheetData = worksheet.GetFirstChild<SheetData>();
sheetData.Append(row);
A Full Example
using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create(tmp, SpreadsheetDocumentType.Workbook))
{
// Add a WorkbookPart to the document.
WorkbookPart workbookpart = spreadsheetDocument.AddWorkbookPart();
workbookpart.Workbook = new Workbook();
// Add a WorksheetPart to the WorkbookPart.
WorksheetPart worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet(new SheetData());
// Add Sheets to the Workbook.
Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.
AppendChild<Sheets>(new Sheets());
// Append a new worksheet and associate it with the workbook.
Sheet sheet = new Sheet()
{
Id = spreadsheetDocument.WorkbookPart.
GetIdOfPart(worksheetPart),
SheetId = 1,
Name = fileName,
};
sheets.Append(sheet);
var firstChild = sheet.FirstChild;
//sheet.Append(row);
Worksheet worksheet = worksheetPart.Worksheet;
SheetData sheetData = worksheet.GetFirstChild<SheetData>();
UInt32 rowIndex = 1;
var row = new Row() { RowIndex = rowIndex };
var firstNameCell = new Cell() { CellReference = "A" + rowIndex };
firstNameCell.CellValue = new CellValue("FirstName");
firstNameCell.DataType = CellValues.String;
row.Append(firstNameCell);
Cell lastNameCell = new Cell() { CellReference = "B" + rowIndex };
lastNameCell.CellValue = new CellValue("LastName");
lastNameCell.DataType = new EnumValue<CellValues>(CellValues.String);
row.Append(lastNameCell);
sheetData.Append(row);
workbookpart.Workbook.Save();
// Close the document.
spreadsheetDocument.Close();
}

How can we insert the next row of the excel sheet if the current excel sheet having the records?

How can we able to write next row of the excel sheet if it ave records during exporting data from c#
it is the code i used for exporting data. to excel . i failed to export the data to next line by this code
private void ExportToOxml(bool firstTime)
{
if (count == 0)
{
ResultsData.Columns.Remove("TotalRecords");
ResultsData.Columns.Remove("PageIndex");
// fileName = #"C:\MyExcel.csv";
//Delete the file if it exists.
if (firstTime && File.Exists(xsfd.FileName))
{
File.Delete(fileName);
}
count++;
}
if (firstTime)
{
//This is the first time of creating the excel file and the first sheet.
// Create a spreadsheet document by supplying the filepath.
// By default, AutoSave = true, Editable = true, and Type = xlsx.
SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.
Create(fileName, SpreadsheetDocumentType.Workbook);
// Add a WorkbookPart to the document.
WorkbookPart workbookpart = spreadsheetDocument.AddWorkbookPart();
workbookpart.Workbook = new Workbook();
// Add a WorksheetPart to the WorkbookPart.
var worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
var sheetData = new SheetData();
worksheetPart.Worksheet = new Worksheet(sheetData);
var bold1 = new System.Windows.Documents.Bold();
CellFormat cf = new CellFormat();
// Add Sheets to the Workbook.
Sheets sheets;
sheets = spreadsheetDocument.WorkbookPart.Workbook.
AppendChild<Sheets>(new Sheets());
// Append a new worksheet and associate it with the workbook.
var sheet = new Sheet()
{
Id = spreadsheetDocument.WorkbookPart.
GetIdOfPart(worksheetPart),
SheetId = sheetId,
Name = "Sheet" + sheetId
};
sheets.Append(sheet);
//Add Header Row.
var headerRow = new Row();
foreach (DataColumn column in ResultsData.Columns)
{
var cell = new Cell { DataType = CellValues.String, CellValue = new CellValue(column.ColumnName) };
headerRow.AppendChild(cell);
}
sheetData.AppendChild(headerRow);
foreach (DataRow row in ResultsData.Rows)
{
var newRow = new Row();
foreach (DataColumn col in ResultsData.Columns)
{
var cell = new Cell
{
DataType = CellValues.String,
CellValue = new CellValue(row[col].ToString())
};
newRow.AppendChild(cell);
}
sheetData.AppendChild(newRow);
}
workbookpart.Workbook.Save();
spreadsheetDocument.Close();
}
else
{
// Open the Excel file that we created before, and start to add sheets to it.
var spreadsheetDocument = SpreadsheetDocument.Open(fileName, true);
var workbookpart = spreadsheetDocument.WorkbookPart;
if (workbookpart.Workbook == null)
workbookpart.Workbook = new Workbook();
var worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
var sheetData = new SheetData();
worksheetPart.Worksheet = new Worksheet(sheetData);
var sheets = spreadsheetDocument.WorkbookPart.Workbook.Sheets;
if (sheets.Elements<Sheet>().Any())
{
//Set the new sheet id
sheetId = sheets.Elements<Sheet>().Max(s => s.SheetId.Value) + 1;
}
else
{
sheetId = 1;
}
// Append a new worksheet and associate it with the workbook.
var sheet = new Sheet()
{
Id = spreadsheetDocument.WorkbookPart.
GetIdOfPart(worksheetPart),
SheetId = sheetId,
Name = "Sheet" + sheetId
};
sheets.Append(sheet);
//Add the header row here.
var headerRow = new Row();
foreach (DataColumn column in ResultsData.Columns)
{
var cell = new Cell { DataType = CellValues.String, CellValue = new CellValue(column.ColumnName) };
headerRow.AppendChild(cell);
}
sheetData.AppendChild(headerRow);
foreach (DataRow row in ResultsData.Rows)
{
var newRow = new Row();
foreach (DataColumn col in ResultsData.Columns)
{
var cell = new Cell
{
DataType = CellValues.String,
CellValue = new CellValue(row[col].ToString())
};
newRow.AppendChild(cell);
}
sheetData.AppendChild(newRow);
}
workbookpart.Workbook.Save();
// Close the document.
spreadsheetDocument.Close();
}
}

Categories

Resources