ASP.NETMVC如何使用EPPlus導(dǎo)出數(shù)據(jù)到Excel中-創(chuàng)新互聯(lián)

小編給大家分享一下ASP.NET MVC如何使用EPPlus導(dǎo)出數(shù)據(jù)到Excel中,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!

創(chuàng)新互聯(lián)專注于九原企業(yè)網(wǎng)站建設(shè),成都響應(yīng)式網(wǎng)站建設(shè)公司,商城網(wǎng)站建設(shè)。九原網(wǎng)站建設(shè)公司,為九原等地區(qū)提供建站服務(wù)。全流程按需定制網(wǎng)站,專業(yè)設(shè)計(jì),全程項(xiàng)目跟蹤,創(chuàng)新互聯(lián)專業(yè)和態(tài)度為您提供的服務(wù)

正文

ASP.NET MVC如何使用EPPlus導(dǎo)出數(shù)據(jù)到Excel中

上面是我們的項(xiàng)目。

首先我們需要引入:EPPlus。

ASP.NET MVC如何使用EPPlus導(dǎo)出數(shù)據(jù)到Excel中

我這里已經(jīng)引入了。

當(dāng)我們在程序中使用ORM的時(shí)候,我們通常將數(shù)據(jù)保存在集合中。集合中的數(shù)據(jù)不能直接導(dǎo)出到Excel文件中。這也就是我們?yōu)樯叮枰葘ist轉(zhuǎn)DataTable的原因。

ASP.NET MVC如何使用EPPlus導(dǎo)出數(shù)據(jù)到Excel中

圖1 :導(dǎo)出Excel的步驟

為了完成這篇文章:我們需要四個(gè)步驟

1.數(shù)據(jù):這里我使用靜態(tài)數(shù)據(jù),來確保這篇文章盡可能通俗易懂。

2.集合:靜態(tài)數(shù)據(jù)保存在集合中

3.DataTable:轉(zhuǎn)化泛型集合的數(shù)據(jù),保存到DataTable中

4.導(dǎo)出文件:DataTable導(dǎo)出為Excel

首先,我們創(chuàng)建一個(gè)類:

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; }
 }
Student

然后創(chuàng)建一個(gè)靜態(tài)數(shù)據(jù)類:

public class StaticDataOfStudent
 {
  public static List<Student> ListStudent
  {
   get 
   {
    return 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},
    };
   }
  }
 }
StaticDataOfStudent

然后就是我們的導(dǎo)出Excel幫助類了:

/// <summary>
 /// Excel導(dǎo)出幫助類
 /// </summary>
 public class ExcelExportHelper
 {
  public static string ExcelContentType
  {
   get 
   {
 return "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">//是否顯示行編號(hào)</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 = null;
   using(ExcelPackage package=new ExcelPackage())
   {
    ExcelWorksheet workSheet = package.Workbook.Worksheets.Add(string.Format("{0}Data", heading));
    int startRowFrom = string.IsNullOrEmpty(heading) ? 1 : 3; //開始的行
    //是否顯示行編號(hào)
    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 = OfficeOpenXml.Style.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<T>(data), heading, isShowSlNo, ColumnsToTake); 
  }
 }

到此為止,后端服務(wù)器的代碼,基本搞完,現(xiàn)在開始設(shè)計(jì)我們的前端代碼:

我們創(chuàng)建一個(gè)ViewModel,用來顯示數(shù)據(jù):

public class StudentViewModel
 {
  public List<Student> ListStudent
  {
   get 
   {
    return StaticDataOfStudent.ListStudent;
   }
  }
 }

然后創(chuàng)建一個(gè)控制器:

 public class HomeController : Controller
 {
  // GET: Home
  public ActionResult Index()
  {
   StudentViewModel model = new StudentViewModel();
   return View(model);
  }
  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"); 
  }
 }

我們的視圖代碼:

@model ExportToExcel.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>

效果圖:

ASP.NET MVC如何使用EPPlus導(dǎo)出數(shù)據(jù)到Excel中

點(diǎn)擊Export之后,就導(dǎo)出了Excel文件到瀏覽器中:打開之后。

ASP.NET MVC如何使用EPPlus導(dǎo)出數(shù)據(jù)到Excel中

總結(jié):這個(gè)導(dǎo)出幫助類,可以定制導(dǎo)出那些列。

   string[] columns = { "ID", "Name","Age"};
   byte[] filecontent = ExcelExportHelper.ExportExcel(lstStudent,"", false, columns);
   return File(filecontent, ExcelExportHelper.ExcelContentType, "MyStudent.xlsx");

這里我只是導(dǎo)出這三列。

看完了這篇文章,相信你對“ASP.NET MVC如何使用EPPlus導(dǎo)出數(shù)據(jù)到Excel中”有了一定的了解,如果想了解更多相關(guān)知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝各位的閱讀!

文章題目:ASP.NETMVC如何使用EPPlus導(dǎo)出數(shù)據(jù)到Excel中-創(chuàng)新互聯(lián)
本文網(wǎng)址:http://muchs.cn/article44/dhicee.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供小程序開發(fā)、自適應(yīng)網(wǎng)站、商城網(wǎng)站、定制網(wǎng)站、響應(yīng)式網(wǎng)站、全網(wǎng)營銷推廣

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

h5響應(yīng)式網(wǎng)站建設(shè)