• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C#EPPlus导出Excel

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

一、Excel导出帮助类    /*引用NuGet包 EPPlus*/

 

     /*引用NuGet包 EPPlus Version=5.0.3 */
        /// <summary>
        /// Excel导出帮助类
        /// </summary>
        public class ExcelExportHelper
        {
            public static string ExcelContentType => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            /// <summary>
            /// List转DataTable
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="data"></param>
            /// <returns></returns>
            public static DataTable ListToDataTable<T>(List<T> data)
            {
                PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
                DataTable dataTable = new DataTable();
                for (int i = 0; i < properties.Count; i++)
                {
                    PropertyDescriptor property = properties[i];
                    dataTable.Columns.Add(property.Name, Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType);
                }
                object[] values = new object[properties.Count];
                foreach (T item in data)
                {
                    for (int i = 0; i < values.Length; i++)
                    {
                        values[i] = properties[i].GetValue(item);
                    }
                    dataTable.Rows.Add(values);
                }
                return dataTable;
            }

            /// <summary>
            /// 导出Excel
            /// </summary>
            /// <param name="dataTable">数据源</param>
            /// <param name="heading">工作簿Worksheet</param>
            /// <param name="showSrNo">//是否显示行编号</param>
            /// <param name="columnsToTake">要导出的列</param>
            /// <returns></returns>
            public static byte[] ExportExcel(DataTable dataTable, string heading = "", bool showSrNo = false, params string[] columnsToTake)
            {
                byte[] result;
                using (ExcelPackage package = new ExcelPackage())
                {
                    ExcelWorksheet workSheet = package.Workbook.Worksheets.Add($"{heading}Data");
                    int startRowFrom = string.IsNullOrEmpty(heading) ? 1 : 3;  //开始的行
                                                                               //是否显示行编号
                    if (showSrNo)
                    {
                        DataColumn dataColumn = dataTable.Columns.Add("#", typeof(int));
                        dataColumn.SetOrdinal(0);
                        int index = 1;
                        foreach (DataRow item in dataTable.Rows)
                        {
                            item[0] = index;
                            index++;
                        }
                    }
                    //Add Content Into the Excel File
                    workSheet.Cells["A" + startRowFrom].LoadFromDataTable(dataTable, true);
                    // autofit width of cells with small content  
                    int columnIndex = 1;
                    foreach (DataColumn item in dataTable.Columns)
                    {
                        if (item.DataType == typeof(DateTime))
                        {
                            var i = dataTable.Columns.IndexOf(item);
                            //设置列格式为自定义 "yyyy/MM/dd HH:mm:ss"
                            workSheet.Cells[2, i + 1, dataTable.Rows.Count + 1, i + 1].Style.Numberformat.Format = "yyyy/MM/dd HH:mm";
                        }
                        ExcelRange columnCells = workSheet.Cells[workSheet.Dimension.Start.Row, columnIndex, workSheet.Dimension.End.Row, columnIndex];
                        int maxLength = columnCells.Max(cell => cell.Value == null || cell.Value is DBNull || string.IsNullOrEmpty(cell.Value.ToString()) ? 0 : cell.Value.ToString().Count());
                        if (maxLength < 150)
                        {
                            workSheet.Column(columnIndex).AutoFit();
                        }
                        columnIndex++;
                    }
                    // format header - bold, yellow on black  
                    using (ExcelRange r = workSheet.Cells[startRowFrom, 1, startRowFrom, dataTable.Columns.Count])
                    {
                        r.Style.Font.Color.SetColor(System.Drawing.Color.White);
                        r.Style.Font.Bold = true;
                        r.Style.Fill.PatternType = ExcelFillStyle.Solid;
                        r.Style.Fill.BackgroundColor.SetColor(System.Drawing.ColorTranslator.FromHtml("#1fb5ad"));
                    }
                    // format cells - add borders  
                    using (ExcelRange r = workSheet.Cells[startRowFrom + 1, 1, startRowFrom + dataTable.Rows.Count, dataTable.Columns.Count])
                    {
                        r.Style.Border.Top.Style = ExcelBorderStyle.Thin;
                        r.Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
                        r.Style.Border.Left.Style = ExcelBorderStyle.Thin;
                        r.Style.Border.Right.Style = ExcelBorderStyle.Thin;
                        r.Style.Border.Top.Color.SetColor(System.Drawing.Color.Black);
                        r.Style.Border.Bottom.Color.SetColor(System.Drawing.Color.Black);
                        r.Style.Border.Left.Color.SetColor(System.Drawing.Color.Black);
                        r.Style.Border.Right.Color.SetColor(System.Drawing.Color.Black);
                    }
                    // removed ignored columns  
                    for (int i = dataTable.Columns.Count - 1; i >= 0; i--)
                    {
                        if (i == 0 && showSrNo)
                        {
                            continue;
                        }
                        if (!columnsToTake.Contains(dataTable.Columns[i].ColumnName))
                        {
                            workSheet.DeleteColumn(i + 1);
                        }
                    }
                    if (!string.IsNullOrEmpty(heading))
                    {
                        workSheet.Cells["A1"].Value = heading;
                        workSheet.Cells["A1"].Style.Font.Size = 20;
                        workSheet.InsertColumn(1, 1);
                        workSheet.InsertRow(1, 1);
                        workSheet.Column(1).Width = 5;
                    }
                    result = package.GetAsByteArray();
                }
                return result;
            }
            /// <summary>
            /// 导出Excel
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="data"></param>
            /// <param name="heading"></param>
            /// <param name="isShowSlNo"></param>
            /// <param name="columnsToTake"></param>
            /// <returns></returns>
            public static byte[] ExportExcel<T>(List<T> data, string heading = "", bool isShowSlNo = false, params string[] columnsToTake)
            {
                return ExportExcel(ListToDataTable(data), heading, isShowSlNo, columnsToTake);
            }
        }

 

 

 

二、调用

  执行后Excel将会保存到D盘

 string strSql = string.Format(@"SELECT TOP 10 [Name] AS 姓名,[PhoneNumber] AS 手机,[Email] AS 邮箱,[Department] AS 部门 FROM [User]");
 DataTable dt = DBHelper.ExecuteTable(strSql);
 string[] columns = { "姓名", "手机", "邮箱", "部门" };
 byte[] filecontent = ExcelExportHelper.ExportExcel(dt, "", false, columns);
 FileStream fs = new FileStream(@"D:\信息.xlsx", FileMode.Create, FileAccess.Write);
 fs.Write(filecontent, 0, filecontent.Length);
 fs.Flush();
 fs.Close();

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap