C# 使用Epplus导出数据到Excel
生活随笔
收集整理的這篇文章主要介紹了
C# 使用Epplus导出数据到Excel
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
簡介:Epplus是一個(gè)使用Open?Office?XML(Xlsx)文件格式,能讀寫Excel?2007/2010文件的開源組件
功效:支持對excel文檔的匯入?yún)R出,圖表(excel自帶的圖表基本都可以實(shí)現(xiàn))的列印 源代碼下載:https://github.com/caofangsheng93/ExcelExportInMvc 安裝:NuGet 導(dǎo)出思路:?
準(zhǔn)備:
1.創(chuàng)建對象
namespace Models{
??? public class Student
??? {
??????? public int ID { get; set; } public string Name { get; set; } public string Sex { get; set; } public int Age { get; set; } public string Email { get; set; }
??? }
}
1.創(chuàng)建Excel幫助類
using OfficeOpenXml;using OfficeOpenXml.Style;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
namespace Common
{
??? /// <summary>
??? /// Excel導(dǎo)出幫助類
??? /// </summary>
??? public class ExcelExportHelper
??? {
??????? public static string ExcelContentType => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; /// <summary>
??????? /// List轉(zhuǎn)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>
??????? /// 導(dǎo)出Excel
??????? /// </summary>
??????? /// <param name="dataTable">數(shù)據(jù)源</param>
??????? /// <param name="heading">工作簿W(wǎng)orksheet</param>
??????? /// <param name="showSrNo">//是否顯示行編號</param>
??????? /// <param name="columnsToTake">要導(dǎo)出的列</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)
??????????????? {
??????????????????? ExcelRange columnCells = workSheet.Cells[workSheet.Dimension.Start.Row, columnIndex, workSheet.Dimension.End.Row, columnIndex];
??????????????????? int maxLength = columnCells.Max(cell => 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>
??????? /// 導(dǎo)出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);
??????? } }
}
3.獲取數(shù)據(jù)并顯示
//數(shù)據(jù)類 using Models;using System.Collections.Generic; namespace BLL
{
??? //數(shù)據(jù)類
??? public class StaticDataOfStudent
??? {
??????? public static List<Student> ListStudent => new List<Student>
??????? {
??????????? new Student {ID = 1, Name = "曹操", Sex = "男", Email = "caocao@163.com", Age = 24},
??????????? new Student {ID = 2, Name = "李易峰", Sex = "女", Email = "lilingjie@sina.com.cn", Age = 24},
??????????? new Student {ID = 3, Name = "張三豐", Sex = "男", Email = "zhangsanfeng@qq.com", Age = 224},
??????????? new Student {ID = 4, Name = "孫權(quán)", Sex = "男", Email = "sunquan@163.com", Age = 1224},
??????? };
??? }
} //用于顯示的數(shù)據(jù)類 using BLL;
using Models;
using System.Collections.Generic; namespace EPPlusMvcDemo2.Models
{
??? public class StudentViewModel
??? {
??????? public List<Student> ListStudent => StaticDataOfStudent.ListStudent;
??? }
}
實(shí)現(xiàn)部分:
1.控制器
using BLL;using Common;
using EPPlusMvcDemo2.Models;
using Models;
using System.Collections.Generic;
using System.Web.Mvc; namespace EPPlusMvcDemo2.Controllers
{
??? public class HomeController : Controller
??? {
??????? // GET: Home
??????? public ActionResult Index()
??????? {
??????????? StudentViewModel model = new StudentViewModel();
??????????? return View(model);
??????? }
??????? //導(dǎo)出
??????? public FileContentResult ExportToExcel()
??????? {
??????????? List<Student> lstStudent = StaticDataOfStudent.ListStudent;
??????????? string[] columns = { "ID", "Name", "Age" };
??????????? byte[] filecontent = ExcelExportHelper.ExportExcel(lstStudent, "", false, columns);
??????????? return File(filecontent, ExcelExportHelper.ExcelContentType, "MyStudent.xlsx");
??????? }
??? }
}
2.視圖
@model EPPlusMvcDemo2.Models.StudentViewModel@{
??? ViewBag.Title = "Excel文件導(dǎo)出";
}
<div class="panel">
??? <div class="panel-heading">
??????? <a href="@Url.Action("ExportToExcel")" class="btn btn-primary">Export</a>
??? </div>
??? <div class="panel-body">
??????? <table class="table table-striped table-bordered">
??????????? <thead>
??????????? <tr>
??????????????? <th>ID</th>
??????????????? <th>Name</th>
??????????????? <th>Sex</th>
??????????????? <th>Age</th>
??????????????? <th>Email</th>
??????????? </tr>
??????????? </thead>
??????????? <tbody>
??????????? @foreach (var item in Model.ListStudent)
??????????? {
??????????????? <tr>
??????????????????? <td>@item.ID</td>
??????????????????? <td>@item.Name</td>
??????????????????? <td>@item.Sex</td>
??????????????????? <td>@item.Age</td>
??????????????????? <td>@item.Email</td>
??????????????? </tr>
??????????? }
??????????? </tbody>
??????? </table>
??? </div>
</div>
?原文:https://www.cnblogs.com/caofangsheng/p/6149843.html
轉(zhuǎn)載于:https://www.cnblogs.com/zhang1f/p/11093679.html
總結(jié)
以上是生活随笔為你收集整理的C# 使用Epplus导出数据到Excel的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: springBoot整合Ehcache—
- 下一篇: C#从excel中将数据导出到datat