创建一个 Excel 文件

MemoryStream excelMS =  GetExcelFile();
 
 //Using Resposne Stream to Make File Available for User to Download;
 Response.Clear();
 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"));

 Response.BinaryWrite(excelMS.ToArray());
 Response.End();

使用 MIME 类型时要小心。你将为不同的文件格式选择不同的 MIME 类型。对于 EX xltm 扩展名,它将是“application / vnd.ms-excel.template.macroEnabled.12”; xlxs 扩展名为“application / vnd.openxmlformats-officedocument.spreadsheetml.sheet”; MS 支持的不同 MIME 类型在此链接

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"]);
    try
    {
        // 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;
}