建立一個 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;
}