I have a code that creates a new Excel file from Datatable, using OpenXML. When I'm done with creating this file, I want to open It for user but without saving It. Basically, what Excel does in this case is that It opens excel file as "Workbook1", and then If you wish you save It manually. I have this demand because users wants to check if data corresponds before saving file to disk.
That could be done in Interop by Visibility property (I have this solution allready, but problem is that Interop is very slow on huge data so users aren't satisfied with It), but I can't find a way to do same in OpenXML. If anyone has any suggestions, please let me know. Here is my code for creating Excel file:
public void Export_To_Excel_stream(MemoryStream ms, DataTable dt)
{
using (SpreadsheetDocument dokument = SpreadsheetDocument.Create(ms, SpreadsheetDocumentType.Workbook))
{
WorkbookPart workbookPart = dokument.AddWorkbookPart();
workbookPart.Workbook = new Workbook();
WorksheetPart worksheetPart = workbookPart.AddNewPart<WorksheetPart>();
var sheetData = new SheetData();
worksheetPart.Worksheet = new Worksheet(sheetData);
Sheets sheets = workbookPart.Workbook.AppendChild(new Sheets());
Sheet sheet = new Sheet() { Id = workbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = dt.TableName };
sheets.Append(sheet);
//header row
Row header = new Row();
List<String> Cols = new List<string>();
foreach (DataColumn col in dt.Columns)
{
Cols.Add(col.ColumnName);
Cell cell = new Cell
{
DataType = CellValues.String,
CellValue = new CellValue(col.ColumnName)
};
header.AppendChild(cell);
}
sheetData.AppendChild(header);
foreach (DataRow row in dt.Rows)
{
Row new_row = new Row();
foreach (String col in Cols)
{
Cell cell = new Cell
{
DataType = CellValues.String,
CellValue = new CellValue(row[col].ToString())
};
new_row.AppendChild(cell);
}
sheetData.AppendChild(new_row);
}
workbookPart.Workbook.Save();
}