Excel建立多報表程式簡化

  • 1066
  • 0
  • 2019-07-20

Excel報表

時常遇到客戶需要在網頁輸出報表的功能

一直以來都是在需要輸出的地方寫一段關於excel的程式碼

但報表多了重複的程式碼就會越來越多

於是需要一個方法來簡化程式


先建立一個 IExcelMaker

public interface IExcelMaker
{
    string makeExcel(IHostingEnvironment hostingEnvironment,WarehouseContext db,string head, string body);
}

然後建立一個ExcelParser注入剛剛寫的 IExcelMaker

public class ExcelParser
{
    private IExcelMaker _excelMaker;

    public ExcelParser(IExcelMaker excelMaker)
    {
        _excelMaker = excelMaker;
    }

    public string DoParser(IHostingEnvironment hostingEnvironment,WarehouseContext db,string head,string body)
    {
        return _excelMaker.makeExcel(hostingEnvironment,db,head, body);
    }
}

接下來實作 IExcelMaker

比如說現在需要一張出貨單的程式

可以新增一個ExcelMaker.cs

裡面寫上

public class ShipmentMaker : IExcelMaker
{
    IHostingEnvironment _hostingEnvironment;// 取得路徑

    //出貨單
    public XLWorkbook makeExcel(IHostingEnvironment hostingEnvironment, Head head, Body body)
    {
        _hostingEnvironment = hostingEnvironment;
        XLWorkbook workbook;
        //實做功能
        return workbook;
    }
}

這時在需要輸出出貨單的地方就可以使用

ExcelParser shipment = new ExcelParser(new ShipmentMaker());
workbook = shipment.DoParser(_hostingEnvironment,head, body);

如果現在客戶又要多一個進貨單的時候

可以在ExcelMaker.cs裡面多一段進貨單的code

public class ShipmentMaker : IExcelMaker
{
    IHostingEnvironment _hostingEnvironment;// 取得路徑

    //出貨單
    public XLWorkbook makeExcel(IHostingEnvironment hostingEnvironment, Head head, Body body)
    {
        _hostingEnvironment = hostingEnvironment;
        XLWorkbook workbook;
        //實做功能
        return workbook;
    }
}
public class PurchaseMaker : IExcelMaker
{
    IHostingEnvironment _hostingEnvironment;// 取得路徑

    //進貨單
    public XLWorkbook makeExcel(IHostingEnvironment hostingEnvironment, Head head, Body body)
    {
        _hostingEnvironment = hostingEnvironment;
        XLWorkbook workbook;
        //實做功能
        return workbook;
    }
}

這樣就可以比較方便的控制excel輸出像是下面這樣

switch (type)
{
    case "shipment":
        ExcelParser shipment = new ExcelParser(new ShipmentMaker());
        workbook = shipment.DoParser(_hostingEnvironment,head, body);
        break;
    case "purchase":
        ExcelParser purchase = new ExcelParser(new PurchaseMaker());
        workbook = purchase.DoParser(_hostingEnvironment, head, body);
        break;
}

如此就可將excel的一大串程式碼控管在ExcelMaker.cs這一支裡面