数据源从List<T>到DataTable再由DataTable到Excel使用EPPLUS-4533

using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;

namespace Common
{
    public class EpplusToExcel
    {
        ///<summary>
        /// 方式(一)由Datatable通过EPPLUS Ver:4533导出EXCEL
        /// </summary>
        /// <param name="dt">DataTable对象</param>
        /// <param name="fileName">请写物理全路径的.xlsx文件名,用@开头不需要转义,无@需要//双斜杠取消转义</param>
        /// <returns>是否成功导出xlsx</returns>
        public static bool ToExcelByEPPlus(DataTable dt, string fileName)
        {
            bool b = false;
            try
            {
                if (dt == null || dt.Rows.Count == 0)
                {
                    return b;
                }

                var excel = new ExcelPackage();
                var workSheet = excel.Workbook.Worksheets.Add("Sheet1");
                int columnIndexInNo1Row = 1;
                foreach (DataColumn curColumn in dt.Columns)
                {
                    workSheet.Cells[1, columnIndexInNo1Row].Value = curColumn.ColumnName;
                    columnIndexInNo1Row++;
                }
                for (int row = 0; row < dt.Rows.Count; row++)
                {
                    for (int col = 0; col < dt.Columns.Count; col++)
                    {
                        workSheet.Cells[row + 2, col + 1].Value = dt.Rows[row][col];//excel行列索引从1开始
                    }
                }
                //调整列宽自适应
                workSheet.Cells[1, 1, dt.Rows.Count + 1, dt.Columns.Count].AutoFitColumns();
                excel.SaveAs(new System.IO.FileInfo(fileName));
                b = true;
            }
            catch (Exception ex)
            {
                string resStr = ex.Message;
            }
            return b;
        }

        /// <summary>
        /// 由一个List<T>得到一个DataTable,供上面导出使用的数据源
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="items"></param>
        /// <returns></returns>
        public static DataTable ToDataTable<T>(List<T> items)
        {
            DataTable dataTable = new DataTable(typeof(T).Name);

            // 获取所有公共属性
            PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

            foreach (PropertyInfo prop in props)
            {
                // 创建一个DataColumn,绑定到props的属性
                dataTable.Columns.Add(prop.Name, prop.PropertyType);
            }

            foreach (T item in items)
            {
                var values = new object[props.Length];
                for (int i = 0; i < props.Length; i++)
                {
                    values[i] = props[i].GetValue(item, null);
                }
                dataTable.Rows.Add(values);
            }

            return dataTable;
        }
    }
}

 

posted @ 2026-07-14 06:37  techNote  阅读(6)  评论(0)    收藏  举报