Sujeet Raman

Sujeet Raman

  • 799
  • 915
  • 334.3k

How to use “contentent disposition attachment” in OpenXml?

Sep 4 2020 12:26 AM
I have a ASP.NET MVC 4 site that creates an excel file using OPEN XML SDK.My controller method generates the OPEN XML excel document and downloading it .But the user should see the excel file in the browser.
I know
Response.AddHeader("content-disposition", "attachment; filename=" + fileName + "");
is responsible for it.But I dont know how to Impliment this in openXnl methode.I am not using http responce here.Or how can i use? Please help me on this
This is my excel generating methode and I tried to impliment AddHeader "content-disposition" but nothing works
public static void GenerateExcelOpenXML(string FolderPath, DataSet tableSet)
{
WorkbookPart wBookPart = null;
var datetime = DateTime.Now.ToString().Replace("/", "_").Replace(":", "_");
string FilePath = FolderPath + "Report_" + datetime + ".xlsx";
using (SpreadsheetDocument spreadsheetDoc = SpreadsheetDocument.Create(FilePath, SpreadsheetDocumentType.Workbook))
{
wBookPart = spreadsheetDoc.AddWorkbookPart();
wBookPart.Workbook = new Workbook();
uint sheetId = 1;
spreadsheetDoc.WorkbookPart.Workbook.Sheets = new Sheets();
Sheets sheets = spreadsheetDoc.WorkbookPart.Workbook.GetFirstChild<Sheets>();
WorkbookStylesPart wbsp = wBookPart.AddNewPart<WorkbookStylesPart>();
wbsp.Stylesheet = CreateStylesheet();
wbsp.Stylesheet.Save();
foreach (DataTable table in tableSet.Tables)
{
WorksheetPart wSheetPart = wBookPart.AddNewPart<WorksheetPart>();
Sheet sheet = new Sheet() { Id = spreadsheetDoc.WorkbookPart.GetIdOfPart(wSheetPart),
SheetId = sheetId, Name = table.TableName };
sheets.Append(sheet);
SheetData sheetData = new SheetData();
wSheetPart.Worksheet = new Worksheet();
Row headerRow = new Row();
Columns columns = new Columns();
int ColumnNumber = 1;
foreach (DataColumn column in table.Columns)
{
Cell cell = new Cell();
cell.DataType = CellValues.String;
cell.CellValue = new CellValue(column.ColumnName);
cell.StyleIndex = 2;
headerRow.AppendChild(cell);
Column column1 = new Column();
column1.Width = 30;
column1.Min = Convert.ToUInt32(ColumnNumber);
column1.Max = Convert.ToUInt32(ColumnNumber);
column1.CustomWidth = true;
columns.AppendChild(column1);
ColumnNumber = ColumnNumber + 1;
}
wSheetPart.Worksheet.AppendChild(columns);
sheetData.AppendChild(headerRow);
foreach (DataRow dr in table.Rows)
{
Row row = new Row();
foreach (DataColumn column in table.Columns)
{
Cell cell = new Cell();
cell.DataType = CellValues.String;
cell.CellValue = new CellValue(dr[column].ToString());
cell.StyleIndex = 1;
row.AppendChild(cell);
}
sheetData.AppendChild(row);
}
sheetId++;
wSheetPart.Worksheet.AppendChild(sheetData);
//sheetData.AddHeader("content-disposition", "attachment; filename=" + fileName + "");
//how i can impliment here?
}
}
}

Answers (1)