.Net Excel操作之NPOI(二)常用操作封裝


一、Excel數據導出常用操作

1.指定表頭和描述

2.指定數據庫中讀出的數據集合

二、ExcelExport封裝

/// <summary>
/// Excel常用的表格導出邏輯封裝
/// 單表寫入
/// </summary>
public class ExcelExport
{
    /// <summary>
    /// 導出的Excel文件名稱+路徑
    /// </summary>
    public string FullName { get; set; }
    /// <summary>
    /// 導出的字段名稱和描述
    /// </summary>
    public Dictionary<string, string> Fields { get; set; }

    private HSSFWorkbook _workbook = null;
    private ISheet _sheet = null;
    /// <summary>
    /// 創建實例,驗證導出文件名
    /// </summary>
    /// <param name="FullName"></param>
    /// <param name="Fields"></param>
    public ExcelExport(string FullName, Dictionary<string, string> Fields)
    {
        this.FullName = FullName;
        this.Fields = Fields;
        Check();
        _workbook = new HSSFWorkbook();
        _sheet = _workbook.CreateSheet("Sheet1");
    }
    /// <summary>
    /// 驗證Excel文件名
    /// </summary>
    private void Check()
    {
        try
        {
            FileInfo info = new FileInfo(this.FullName);
            string[] extentions = new string[] {
                ".xls",
                ".xlsx"
            };
            if (extentions.Any(q => q == info.Extension) == false)
                throw new Exception("excel文件的擴展名不正確,應該為xls或xlsx");
            if (info.Exists == false)
                info.Create().Close();
        }
        catch (Exception ex)
        {
            throw new Exception("創建Excel文件失敗", ex);
        }
    }

    /// <summary>
    /// 執行導出操作
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="list"></param>
    public void Export<T>(List<T> list)
    {
        //寫入表格頭
        WriteHead();
        //寫入數據
        ICellStyle cellStyle = _workbook.CreateCellStyle();
        cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("@");//為避免日期格式被Excel自動替換,所以設定 format 為 『@』 表示一率當成text來看
        cellStyle.BorderBottom = BorderStyle.Thin;
        cellStyle.BorderLeft = BorderStyle.Thin;
        cellStyle.BorderRight = BorderStyle.Thin;
        cellStyle.BorderTop = BorderStyle.Thin;
        cellStyle.VerticalAlignment = VerticalAlignment.Center;
        cellStyle.Alignment = HorizontalAlignment.Center;

        IFont cellFont = _workbook.CreateFont();
        cellFont.Boldweight = (short)FontBoldWeight.Normal;
        cellStyle.SetFont(cellFont);

        //建立行內容,從1開始
        int rowInex = 1;

        foreach (var rowItem in list)
        {
            //創建行
            IRow row = _sheet.CreateRow(rowInex);
            row.HeightInPoints = 25;

            int cellIndex = 0;
            foreach (var cellItem in this.Fields)
            {
                //創建單元格
                ICell cell = row.CreateCell(cellIndex);
                //反射獲取屬性的值
                PropertyInfo info = rowItem.GetType().GetProperty(cellItem.Key);
                if (info == null)
                {
                    cell.SetCellValue($"'{cellItem.Key}'屬性不存在");
                }
                else
                {
                    object value = info.GetValue(rowItem);
                    if (value != null)
                        cell.SetCellValue(value.ToString());
                }
                cell.CellStyle = cellStyle;
                cellIndex++;
            }
            //進入下一次循環
            rowInex++;
        }

        //自適應列寬度
        for (int i = 0; i < this.Fields.Count; i++)
        {
            _sheet.AutoSizeColumn(i);
        }

        //導出到文件
        WriteFile();
    }
    /// <summary>
    /// 寫入表頭
    /// </summary>
    private void WriteHead()
    {
        //設置表頭樣式
        ICellStyle headStyle = _workbook.CreateCellStyle();
        headStyle.BorderBottom = BorderStyle.Thin;
        headStyle.BorderLeft = BorderStyle.Thin;
        headStyle.BorderRight = BorderStyle.Thin;
        headStyle.BorderRight = BorderStyle.Thin;
        headStyle.Alignment = HorizontalAlignment.Center;
        headStyle.FillForegroundColor = HSSFColor.Blue.Index;
        headStyle.VerticalAlignment = VerticalAlignment.Center;

        IFont headFont = _workbook.CreateFont();
        headFont.Boldweight = (short)FontBoldWeight.Bold;
        headStyle.SetFont(headFont);

        IRow row = _sheet.CreateRow(0);
        row.HeightInPoints = 30;

        int index = 0;
        foreach (var item in this.Fields)
        {
            ICell cell = row.CreateCell(index);
            cell.SetCellValue(item.Value);
            cell.CellStyle = headStyle;
            index++;
        }
    }
    /// <summary>
    /// 創建文件到磁盤
    /// </summary>
    private void WriteFile()
    {
        using (FileStream fs = new FileStream(this.FullName, FileMode.OpenOrCreate))
        {
            _workbook.Write(fs);
            fs.Flush();
            fs.Close();
        }
    }
}

三、使用示例

1.匿名對象集合導出

Dictionary<string, string> fields = new Dictionary<string, string>();
fields.Add("ID", "主鍵");
fields.Add("Name", "姓名");
fields.Add("Age", "年齡");
fields.Add("Birthday", "生日");
ExcelExport _export = new ExcelExport(LocalPathHelper.GetCurrentData() + "/export1.xls", fields);


List<object> list = new List<object>() {
    new {ID=1,Name="張三豐",Age=20,Birthday=DateTime.Now },
    new {ID=2,Name="王芳",Age=30,Birthday=DateTime.Now }
};
_export.Export(list);

2.List集合導出

TestOne _Context = new DBA.TestOne();
List<Member_Info> list = _Context.Member_Info.ToList();
Dictionary<string, string> fields = new Dictionary<string, string>();
fields.Add("MemberID", "主鍵");
fields.Add("code", "賬號");
fields.Add("RealName", "姓名");
fields.Add("IsActive", "是否激活");
fields.Add("commission", "獎金余額");

//使用
ExcelExport _export = new ExcelExport(LocalPathHelper.GetCurrentData() + "\\export2.xls", fields);
//_export.Export(list);
_export.Export<Member_Info>(list);

 

更多:

.Net Excel操作之NPOI(一)簡介

C#中操作剛導出的Excel,設置其為自動調整列寬

C#操作word封裝


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM