iT邦幫忙

0

[C#] EPPlus套件,產生Excel

  • 分享至 

  • xImage
  •  

一、安裝
可於NuGet套件管理員安裝EPPlus加入參考

二、建立類別

/// <summary>Excel欄位資料</summary>
public class MExcelCell
{
    /// <summary>欄位內容</summary>
    public object Content { get; set; } = = string.Empty;
    /// <summary>背景顏色</summary>
    public Color BackgroundColor { get; set; } = Color.White;
    /// <summary>樣式</summary>
    public ExcelFillStyle PatternType { get; set; } = ExcelFillStyle.None;
    /// <summary>數字格式</summary>
    public string NumberFormat { get; set; } = = string.Empty;
    /// <summary>公式</summary>
    public string Formula { get; set; } = = string.Empty;
    /// <summary>文字水平位置</summary>
    public ExcelHorizontalAlignment HorAlign { get; set; } = ExcelHorizontalAlignment.General;
}
/// <summary>Excel方法</summary>
public class CExcelPackage
{
    /// <summary>起始列</summary>
    public int BeginCell { get; set; }
    /// <summary>終點列</summary>
    public int EndCell { get; set; }
    /// <summary>建立Excel</summary>
    private ExcelPackage Epackage = new ExcelPackage();
    /// <summary>建立第一個Sheet,後方為定義Sheet的名稱</summary>
    private ExcelWorksheet Sheet;
    
    /// <summary>加入工作表</summary>
    public void AddSheet(List<List<MExcelCell>> Table, string SheetName)
    {
        //建立一個Sheet,後方為定義Sheet的名稱
        Sheet = Epackage.Workbook.Worksheets.Add(SheetName);

        //內文
        for (int col = 0; col < Table.Count; col++)
        {
            for (int row = 0; row < Table[col].Count; row++)
            {
                int x = col + 1;
                int y = row + 1;
                if (!string.IsNullOrEmpty(Table[col][row].Formula))
                {
                    Sheet.Cells[x, y].Formula = Table[col][row].Formula;
                }
                else
                    Sheet.Cells[x, y].Value = Table[col][row].Content;
                if (!string.IsNullOrEmpty(Table[col][row].NumberFormat))
                    Sheet.Cells[x, y].Style.Numberformat.Format = Table[col][row].NumberFormat;
                if (Table[col][row].PatternType != ExcelFillStyle.None)
                    Sheet.Cells[x, y].Style.Fill.PatternType = Table[col][row].PatternType;
                if (Table[col][row].BackgroundColor != System.Drawing.Color.White)
                    Sheet.Cells[x, y].Style.Fill.BackgroundColor.SetColor(Table[col][row].BackgroundColor);
                Sheet.Cells[x, y].Style.Border.BorderAround(ExcelBorderStyle.Thin);
            }
        }

        //自動調整欄寬
        for (int i = 1; i <= Table[1].Count; i++)
        {
            Sheet.Column(i).AutoFit();
            Sheet.Column(i).Width += 2;
        }
        //高度設定
        for (int i = 3; i <= Table.Count; i++)
        {
            Sheet.Row(i).Height = 20;
        }

        //調整邊距
        decimal inch = 1M / 2.54M;
        Sheet.PrinterSettings.TopMargin = inch;//因為EPPlus單位都是英吋
        Sheet.PrinterSettings.LeftMargin = inch;
        Sheet.PrinterSettings.RightMargin = inch;
        Sheet.PrinterSettings.BottomMargin = inch;

        //取得起始列
        GetBeginCell();
        //取得終點列
        GetEndCell();
    }

    /// <summary>合併儲存格</summary>
    public void MergeColumn(int row1, int col1, int row2, int col2)
    {
        Sheet.Cells[row1, col1, row2, col2].Merge = true;
    }

    /// <summary>設定寬度</summary>
    public void ColumnWidth(int col, int value)
    {
        Sheet.Column(col).Width = value;
    }

    /// <summary>取得起始列</summary>
    public void GetBeginCell()
    {
        string address = Sheet.Dimension.Address;
        string[] cells = address.Split(new char[] { ':' });
        BeginCell = Int32.Parse(Regex.Replace(cells[0], "[^0-9]", ""));
    }

    /// <summary>取得終點列</summary>
    public void GetEndCell()
    {
        string address = Sheet.Dimension.Address;
        string[] cells = address.Split(new char[] { ':' });
        EndCell = Int32.Parse(Regex.Replace(cells[1], "[^0-9]", ""));
    }

    /// <summary>指定列文字對齊(目前測試只有套用到2列以上才會生效)</summary>
    public void Alignment(string range, ExcelHorizontalAlignment HorAlign = ExcelHorizontalAlignment.Center, ExcelVerticalAlignment VerAlign = ExcelVerticalAlignment.Center)
    {
        Sheet.Cells[range].Style.HorizontalAlignment = HorAlign;
        Sheet.Cells[range].Style.VerticalAlignment = VerAlign;
    }

    /// <summary>匯出物件資料</summary>
    public MemoryStream Export()
    {
        //因為ep.Stream是加密過的串流,故要透過SaveAs將資料寫到MemoryStream,
        //在將MemoryStream使用FileStreamResult回傳到前端。
        MemoryStream fileStream = new MemoryStream();
        Epackage.SaveAs(fileStream);
        Epackage.Dispose();
        //如果這邊不下Dispose,建議此ep要用using包起來,
        //但是要記得先將資料寫進MemoryStream在Dispose。
        fileStream.Position = 0;
        //不重新將位置設為0,excel開啟後會出現錯誤
        //經銷商審核資料OR店務資料
        return fileStream;
    }
}

三、使用方法
前端HTML

<form id="formName" action="Export" method="post">
    <input type="text" name="Content" value="test">
</form>

前端JS

$('#formName').attr('action', 'Export').submit();

後端

public ActionResult ExportSalesReport(String Content)
{
    String fileName = "檔案名稱";
    List<List<MExcelCell>> Table = new List<List<MExcelCell>>(); 
    List<MExcelCell> Row = new List<MExcelCell>();
    Row.Add(new MExcelCell {
        Content = Content,
        PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid,
        BackgroundColor = System.Drawing.Color.FromArgb(255, 255, 255),
    });
    Table.Add(Row);

    CExcelPackage cExcelPackage = new CExcelPackage();
    cExcelPackage.AddSheet(Table, fileName);
    
    return File(cExcelPackage.Export(),
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        $"{FileName}.xlsx");
}

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言