一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術|正則表達式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務器之家 - 編程語言 - ASP.NET教程 - ASP.NET MVC使用EPPlus,導出數據到Excel中

ASP.NET MVC使用EPPlus,導出數據到Excel中

2020-04-10 16:07灰太狼的夢想 ASP.NET教程

這篇文章介紹的是怎樣導出數據到Excel文件中,大多數的后端程序都有報表功能:把顯示在Grid中的數據導出到Excel文件中,這篇文章中使用的是EPPlus組件。需要的朋友可以參考借鑒

好久沒寫博客了,今天特地來更新一下,今天我們要學習的是如何導出數據到Excel文件中,這里我使用的是免費開源的Epplus組件。

源代碼下載:https://github.com/caofangsheng93/ExcelExportInMvc

介紹

這篇文章,介紹的是怎樣導出數據到Excel文件中,大多數的后端程序都有報表功能:把顯示在Grid中的數據導出到Excel文件中,這篇文章中使用的是EPPlus組件。

EPPlus是一個基于OOXML【Open Extended Markup Language 】格式的,操作Excel表格的類庫。OOXML是由微軟開發的。默認支持微軟的Office。

開源網站:http://epplus.codeplex.com/

正文

ASP.NET MVC使用EPPlus,導出數據到Excel中

上面是我們的項目。

首先我們需要引入:EPPlus。

ASP.NET MVC使用EPPlus,導出數據到Excel中

我這里已經引入了。

當我們在程序中使用ORM的時候,我們通常將數據保存在集合中。集合中的數據不能直接導出到Excel文件中。這也就是我們為啥,需要先將List轉DataTable的原因。

ASP.NET MVC使用EPPlus,導出數據到Excel中

圖1 :導出Excel的步驟

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

1.數據:這里我使用靜態數據,來確保這篇文章盡可能通俗易懂。

2.集合:靜態數據保存在集合中

3.DataTable:轉化泛型集合的數據,保存到DataTable中

4.導出文件:DataTable導出為Excel

首先,我們創建一個類:

?
1
2
3
4
5
6
7
8
9
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

然后創建一個靜態數據類:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class StaticDataOfStudent
 {
  public static List<Student> ListStudent
  {
   get
   {
    return new List<Student>()
    {
    new Student(){ID=1,Name="曹操",Sex="男",Email="[email protected]",Age=24},
    new Student(){ID=2,Name="李易峰",Sex="女",Email="[email protected]",Age=24},
    new Student(){ID=3,Name="張三豐",Sex="男",Email="[email protected]",Age=224},
    new Student(){ID=4,Name="孫權",Sex="男",Email="[email protected]",Age=1224},
    };
   }
  }
 }
StaticDataOfStudent

然后就是我們的導出Excel幫助類了:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
/// <summary>
 /// Excel導出幫助類
 /// </summary>
 public class ExcelExportHelper
 {
  public static string ExcelContentType
  {
   get
   {
 return "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 = null;
   using(ExcelPackage package=new ExcelPackage())
   {
    ExcelWorksheet workSheet = package.Workbook.Worksheets.Add(string.Format("{0}Data", heading));
    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 = 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>
  /// 導出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);
  }
 }

到此為止,后端服務器的代碼,基本搞完,現在開始設計我們的前端代碼:

我們創建一個ViewModel,用來顯示數據:

?
1
2
3
4
5
6
7
8
9
10
public class StudentViewModel
 {
  public List<Student> ListStudent
  {
   get
   {
    return StaticDataOfStudent.ListStudent;
   }
  }
 }

然后創建一個控制器:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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");
 }
}

我們的視圖代碼:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
@model ExportToExcel.Models.StudentViewModel
@{
 ViewBag.Title = "Excel文件導出";
}
<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,導出數據到Excel中

點擊Export之后,就導出了Excel文件到瀏覽器中:打開之后。

ASP.NET MVC使用EPPlus,導出數據到Excel中

總結:這個導出幫助類,可以定制導出那些列。

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

這里我只是導出這三列。

以上就是本文的全部內容,希望本文的內容對大家的學習或者工作能帶來一定的幫助,同時也希望多多支持服務器之家!

原文鏈接:http://www.cnblogs.com/caofangsheng/p/6149843.html

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 色播影院性播影院私人影院 | 精品国产综合区久久久久久 | 国产精品视频一区二区三区不卡 | 免费视频 | 精品久久国产 | 精品小视频在线 | 国产精品亚洲va在线观看 | 国产目拍亚洲精品一区二区三区 | 色综合久久中文字幕综合网 | 黄色wwwwww | 国产免费色视频 | 色偷偷亚洲男人 | 色多多视频在线 | 青草福利视频 | 天美传媒tm0065 | 国产视频三区 | 色操网 | 欧美亚洲国产另类在线观看 | 国产精品aⅴ | 国产欧美精品专区一区二区 | 美女撒尿毛片免费看 | 亚洲国产视频网站 | 扒开老女人 | 男女男精品视频 | 刺客女仆| 色姑娘导航 | 三叶草私人研究所 | 欧美一区二区三区四区五区六区 | 热久久天天拍天天拍热久久2018 | 欧洲肥女大肥臀 | 国产精品原创永久在线观看 | 免费又爽又黄禁片视频在线播放 | 青青青草国产 | 动漫女性扒开尿口羞羞漫画 | 亚洲视频99 | 国产成人在线视频 | 亚洲成年人在线观看 | 欧美日韩久久中文字幕 | 国产精品猎奇系列在线观看 | china中国xxxxfree| 日韩亚洲人成网站在线播放 |