apache-poi Create a Excel file


MemoryStream excelMS =  GetExcelFile();
 //Using Resposne Stream to Make File Available for User to Download;
 Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
 Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", @"Excel_" + DateTime.Now.ToString("yyyy-dd-M-HH-mm") + ".xlsx"));


be careful while using MIME type. you'll have select different MIME types for different file formats. For EX xltm extension it will be "application/vnd.ms-excel.template.macroEnabled.12"; xlxs extension it will be "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; Different MIME types supported MS is at this link.

public MemoryStream GetExcelFile()
    //Excel File Stream 
    MemoryStream ms = null;
    // create workbook
    XSSFWorkbook workbook = new XSSFWorkbook();
    // the table named mySheet
    //Assigning New Sheet Name /
    XSSFSheet sheet = (XSSFSheet)workbook.CreateSheet("WorkSheet");
    // Assuming FreezePaneRow  = 10, FreezePaneColumn = 11 in the config file
    int freezeRow = Convert.ToInt32(ConfigurationManager.AppSettings["FreezePaneRow"]);
    int freezeCol = Convert.ToInt32(ConfigurationManager.AppSettings["FreezePaneCol"]);
        // Freeze Created Excel Sheet Row;
            sheet.CreateFreezePane(freezeCol, freezeRow, freezeCol, freezeRow);
        //Freezing only the Header Row;
            sheet.CreateFreezePane(0, 1);

         using (ms = new MemoryStream())
                logger.Info("Using Memory Stream to Create New WorkBook");
                workbook.Write(ms); // Write to memory stream for download through browser     
    catch (Exception Ex)
    { ... }
    return ms;