萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

ASP.NET 使用 NPOI 讀取 Excel 模板匯出下載完整實作指南

為什麼選擇 NPOI 而非 Office Interop?

問題Office InteropNPOI 純 .NET 實作
伺服器需安裝 Office是 (授權成本、安全風險)否 (零依賴)
COM 物件權限設定複雜 (DCOM 配置、身分模擬)不需要
進程殘留風險高 (Excel.exe 殭屍進程)無 (純 managed code)
併發處理極差 (單執行緒 COM)優秀 (執行緒安全)
數值格式自動轉換是 (000123 → 123)可控制 (設定 CellType = String)
公式前綴誤判是 (=、- 開頭視為公式)可控制 (SetCellType)
前 8 列型別推斷錯誤是 (混合型別導致科學記號)明確指定型別
匯出速度慢 (進程間通訊)快 (記憶體內操作)

NPOI 版本與安裝

  • NPOI 1.2.5:.NET Framework 2.0/3.5/4.x 經典版本 (本文使用)
  • NPOI 2.x:.NET Standard 2.0+,支援 .NET Core / .NET 5+
  • NuGet 安裝:`Install-Package NPOI` (自動解析相依 `NPOI.OOXML` 等)

核心命名空間

using NPOI.HSSF.UserModel;   // .xls (BIFF8)
using NPOI.XSSF.UserModel;   // .xlsx (OOXML)
using NPOI.SS.UserModel;     // 通用介面 (IWorkbook, ISheet, IRow, ICell)
using System.IO;

四步驟完整匯出流程

步驟 1:載入模板檔案到工作簿

IWorkbook workbook;

// .xls 格式
using (var fs = new FileStream(templatePath, FileMode.Open, FileAccess.Read))
{
    workbook = new HSSFWorkbook(fs);
}

// .xlsx 格式
// using (var fs = new FileStream(templatePath, FileMode.Open, FileAccess.Read))
// {
//     workbook = new XSSFWorkbook(fs);
// }

步驟 2:根據模板填充資料

ISheet sheet = workbook.GetSheet("Sheet1"); // 取得指定工作表

// 方式 A:模板已有列,直接填值
sheet.GetRow(1).GetCell(1).SetCellValue(200200);
sheet.GetRow(2).GetCell(1).SetCellValue(300);
// ...

// 方式 B:動態建立列 (資料筆數不固定)
for (int i = 0; i < dataList.Count; i++)
{
    IRow row = sheet.CreateRow(startRow + i); // 或 GetRow 後建立 Cell
    row.CreateCell(0).SetCellValue(dataList[i].Id);
    row.CreateCell(1).SetCellValue(dataList[i].Name);
    row.CreateCell(2).SetCellValue(dataList[i].Amount);
    // 設定儲存格樣式...
}

// 強制重新計算公式 (模板含公式時必要)
sheet.ForceFormulaRecalculation = true;

步驟 3:設定 HTTP 回應標頭


// 瀏覽器識別為 Excel 檔案下載
Response.ContentType = "application/vnd.ms-excel"; // .xls
// Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; // .xlsx

// 檔名編碼處理 (避免中文檔名亂碼)
string fileName = "匯出報表_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
string encodedName = HttpUtility.UrlEncode(fileName, Encoding.UTF8);
Response.AddHeader("Content-Disposition", $"attachment;filename={encodedName}");

Response.Clear(); // 清除輸出緩衝

步驟 4:寫入記憶體流並輸出到客戶端

using (var ms = new MemoryStream())
{
    workbook.Write(ms);           // 寫入記憶體流
    Response.BinaryWrite(ms.GetBuffer()); // 二進位輸出
    Response.End();               // 結束回應
}

完整整合範例 (ExportExcel.ashx - 一般處理程式最適合)

<%@ WebHandler Language="C#" Class="ExportExcelHandler" %>
using System;
using System.IO;
using System.Web;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;

public class ExportExcelHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        try
        {
            string templatePath = context.Server.MapPath("~/Templates/ReportTemplate.xls");
            
            IWorkbook workbook;
            using (var fs = new FileStream(templatePath, FileMode.Open, FileAccess.Read))
                workbook = new HSSFWorkbook(fs);

            ISheet sheet = workbook.GetSheet("ReportData");
            
            // 模擬資料來源 (實際從 DB 取得)
            var data = GetReportData();
            
            // 填充資料 (假設模板第 0 列為標題,資料從第 1 列開始)
            for (int i = 0; i < data.Count; i++)
            {
                IRow row = sheet.GetRow(i + 1) ?? sheet.CreateRow(i + 1);
                row.GetCell(0)?.SetCellValue(data[i].ItemNo);
                row.GetCell(1)?.SetCellValue(data[i].ProductName);
                row.GetCell(2)?.SetCellValue(data[i].Quantity);
                row.GetCell(3)?.SetCellValue(data[i].UnitPrice);
                row.GetCell(4)?.SetCellValue(data[i].TotalPrice);
            }
            
            sheet.ForceFormulaRecalculation = true;

            // 設定回應
            context.Response.ContentType = "application/vnd.ms-excel";
            string fileName = $"報表_{DateTime.Now:yyyyMMdd_HHmmss}.xls";
            context.Response.AddHeader("Content-Disposition", 
                "attachment;filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
            context.Response.Clear();

            using (var ms = new MemoryStream())
            {
                workbook.Write(ms);
                context.Response.BinaryWrite(ms.GetBuffer());
            }
        }
        catch (Exception ex)
        {
            context.Response.ContentType = "text/plain";
            context.Response.Write("匯出失敗:" + ex.Message);
        }
        finally
        {
            context.Response.End();
        }
    }

    public bool IsReusable => false;

    private List GetReportData() 
    {
        // 實際從資料庫查詢
        return new List 
        {
            new ReportItem { ItemNo="001", ProductName="筆電", Quantity=10, UnitPrice=25000, TotalPrice=250000 },
            new ReportItem { ItemNo="002", ProductName="滑鼠", Quantity=50, UnitPrice=500, TotalPrice=25000 }
        };
    }
}

public class ReportItem 
{
    public string ItemNo { get; set; }
    public string ProductName { get; set; }
    public int Quantity { get; set; }
    public decimal UnitPrice { get; set; }
    public decimal TotalPrice { get; set; }
}

進階技巧:儲存格樣式與格式化

// 建立共用樣式 (效能優於逐儲存格設定)
ICellStyle headerStyle = workbook.CreateCellStyle();
headerStyle.FillForegroundColor = IndexedColors.Grey25Percent.Index;
headerStyle.FillPattern = FillPattern.SolidForeground;
headerStyle.BorderTop = headerStyle.BorderBottom = headerStyle.BorderLeft = headerStyle.BorderRight = BorderStyle.Thin;
var headerFont = workbook.CreateFont();
headerFont.Boldweight = (short)FontBoldWeight.Bold;
headerStyle.SetFont(headerFont);

// 數值格式:千分位 + 2 位小數
ICellStyle numberStyle = workbook.CreateCellStyle();
numberStyle.DataFormat = workbook.CreateDataFormat().GetFormat("#,##0.00");

// 日期格式
ICellStyle dateStyle = workbook.CreateCellStyle();
dateStyle.DataFormat = workbook.CreateDataFormat().GetFormat("yyyy/mm/dd");

// 套用樣式
cell.CellStyle = numberStyle;

常見問題排查

問題原因解決方案
導出檔案損毀/0 bytesResponse 輸出前有其他輸出/空白字元使用 `.ashx` 或 `Response.Clear()` 確保純淨輸出
中文檔名下載亂碼瀏覽器編碼解析不一致`HttpUtility.UrlEncode(fileName, Encoding.UTF8)`
數值變科學記號 (1.23E+10)儲存格格式為 General設定 `DataFormat` 或 `SetCellType(CellType.String)`
日期顯示為數字 (44927)未設定日期格式套用 `dateStyle` 或 `cell.SetCellValue(DateTime)` 後設定格式
公式不計算Excel 開啟前未計算`sheet.ForceFormulaRecalculation = true`
大量資料 OutOfMemory全部載入記憶體使用 SXSSF (串流寫入) 或分批導出

.NET Core / .NET 5+ 遷移提示

  • 安裝 `NPOI` NuGet 套件 (已支援 .NET Standard 2.0)
  • 將 `HttpContext.Current` 改為注入 `IHttpContextAccessor` 或 Controller 中的 `Response`
  • 檔案路徑使用 `IWebHostEnvironment.WebRootPath` 或 `ContentRootPath`
  • 考慮使用 `FileStreamResult` 回傳檔案:`return File(ms.ToArray(), contentType, fileName);`

總結

NPOI 是 ASP.NET 伺服端 Excel 匯出的黃金標準:零 Office 依賴、高效能、支援複雜樣式與公式。掌握「載入模板 → 填充資料 → 設定回應 → 串流輸出」四步驟核心流程,配合樣式複用、格式化控制、錯誤處理,即可建立穩健的報表匯出功能。現代專案建議遷移至 NPOI 2.x + .NET Core 架構獲得長期支援。

copyright © 萬盛學電腦網 all rights reserved