I have datatable that I'm populating with data and passing through to a method which is supposed to write the data to a memory stream and save it as an Excel spreadsheet. The datatable is correctly populated, but when the memorystream writes it, the capacity of the memorystream is 0. It's as though it just doesn't write anything. Could this be caused by some sort of memory leak? Below is my code that I use to write the workbook (populated by the datatable) using the memorystream
public static MemoryStream Grid_Export_Excel(DataTable data)
{
try
{
var workbook = new XSSFWorkbook();
var sheet = workbook.CreateSheet();
var headerRow = sheet.CreateRow(0);
// Set the column names in the header row
for (int i = 0; i < data.Columns.Count; i++)
headerRow.CreateCell(i).SetCellValue(data.Columns[i].ColumnName);
// Freeze the header row so that it's not scrolled
sheet.CreateFreezePane(0, 1, 0, 1);
for (int r = 0; r < data.Rows.Count; r++)
{
// Create a new row
var row = sheet.CreateRow(r + 1);
// Get the DataRow
var dataRow = data.Rows[r];
for (int c = 0; c < data.Columns.Count; c++)
{
// Get the fieldname
var fieldname = data.Columns[c].ColumnName;
// Make sure that the field exists in the datarow
if (!dataRow.Table.Columns.Contains(fieldname))
continue;
// Create the cell in the row
row.CreateCell(c).SetCellValue(dataRow[fieldname].ToString());
}
}
// Write the workbook to a stream and return as FileStreamResult
MemoryStream ms = new MemoryStream();
workbook.Write(ms);
return ms;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}