Category / Section
In web application, how to avoid file corruption while opening the generated file using XlsIO?
1 min read
XlsIO generated file will be downloaded as .xls format in some browsers by default, even when we add the extension in the file name or set the version for the file. Because of this the downloaded file gets corrupted. To overcome this, set ExcelHttpContentType while saving the file in XlsIO.
Below code snippet demonstrates on how to set ExcelHttpContentType while saving .xlsx format file using XlsIO.
C#
//Step 1 : Instantiate the spreadsheet creation engine. ExcelEngine excelEngine = new ExcelEngine(); //Step 2 : Instantiate the excel application object. IApplication application = excelEngine.Excel; //Creating the workbook with IWorkbook workbook = application.Workbooks.Create(1); //The first worksheet object in the worksheets collection is accessed. IWorksheet sheet = workbook.Worksheets[0]; //Workbook version is set workbook.Version = ExcelVersion.Excel2010; string filename = "Sample.xlsx"; //ExcelHttoContentType is set as file version workbook.SaveAs(filename, HttpContext.ApplicationInstance.Response, ExcelDownloadType.Open, ExcelHttpContentType.Excel2010);
VB
'Step 1 : Instantiate the spreadsheet creation engine. Dim excelEngine As ExcelEngine = New ExcelEngine() 'Step 2 : Instantiate the excel application object. Dim application As IApplication = excelEngine.Excel 'Creating the workbook with Dim workbook As IWorkbook = application.Workbooks.Create(1) 'The first worksheet object in the worksheets collection is accessed. Dim sheet As IWorksheet = workbook.Worksheets(0) 'Workbook version is set workbook.Version = ExcelVersion.Excel2010 Dim filename As String = "Sample.xlsx" 'ExcelHttoContentType is set as file version workbook.SaveAs(filename, HttpContext.ApplicationInstance.Response, ExcelDownloadType.Open, ExcelHttpContentType.Excel2010)
The sample illustrating this can be downloaded here.