最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

 更新時(shí)間:2016年12月11日 15:50:08   作者:灰太狼的夢(mèng)想  
這篇文章介紹的是怎樣導(dǎo)出數(shù)據(jù)到Excel文件中,大多數(shù)的后端程序都有報(bào)表功能:把顯示在Grid中的數(shù)據(jù)導(dǎo)出到Excel文件中,這篇文章中使用的是EPPlus組件。需要的朋友可以參考借鑒

好久沒寫博客了,今天特地來更新一下,今天我們要學(xué)習(xí)的是如何導(dǎo)出數(shù)據(jù)到Excel文件中,這里我使用的是免費(fèi)開源的Epplus組件。

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

介紹

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

EPPlus是一個(gè)基于OOXML【Open Extended Markup Language 】格式的,操作Excel表格的類庫(kù)。OOXML是由微軟開發(fā)的。默認(rèn)支持微軟的Office。

開源網(wǎng)站:http://epplus.codeplex.com/

正文

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

首先我們需要引入:EPPlus。

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

當(dāng)我們?cè)诔绦蛑惺褂肙RM的時(shí)候,我們通常將數(shù)據(jù)保存在集合中。集合中的數(shù)據(jù)不能直接導(dǎo)出到Excel文件中。這也就是我們?yōu)樯?,需要先將List轉(zhuǎn)DataTable的原因。

圖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>

效果圖:

點(diǎn)擊Export之后,就導(dǎo)出了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)出這三列。

以上就是本文的全部?jī)?nèi)容,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來一定的幫助,同時(shí)也希望多多支持腳本之家!

相關(guān)文章

  • ASP.NET XmlHttp跨域訪問實(shí)現(xiàn)代碼

    ASP.NET XmlHttp跨域訪問實(shí)現(xiàn)代碼

    最近項(xiàng)目需要實(shí)現(xiàn)XmlHttp的POST方法到另一服務(wù)器上的頁(yè)面進(jìn)行數(shù)據(jù)的更新,可是IE會(huì)提出“該頁(yè)正在訪問其控制范圍之外的信息,是否繼續(xù)?”等警告信息,而在其他瀏覽器上直接禁止掉,GOOGLE一下原來是XmlHttp的跨域訪問問題,找了很多資料,說是提供很多解決方案,可是都沒有用處。
    2008-11-11
  • .NET?6?跨服務(wù)器聯(lián)表查詢操作MySql、Oracle、SqlServer等相互聯(lián)表

    .NET?6?跨服務(wù)器聯(lián)表查詢操作MySql、Oracle、SqlServer等相互聯(lián)表

    這篇文章主要介紹了.NET?6?跨服務(wù)器聯(lián)表查詢,?MySql、Oracle、SqlServer等相互聯(lián)表,在這里給大家普及下什么是多庫(kù)架構(gòu)ORM就是說一個(gè)對(duì)象可以同時(shí)操作和管理多個(gè)數(shù)據(jù)庫(kù) 我們稱為多庫(kù)架構(gòu),本文結(jié)合實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下
    2022-10-10
  • WPF自定義搜索框代碼分享

    WPF自定義搜索框代碼分享

    這篇文章主要為大家詳細(xì)介紹了WPF自定義搜索框代碼,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2016-09-09
  • asp.net 將一個(gè)圖片以二進(jìn)制值的形式存入Xml文件中的實(shí)例代碼

    asp.net 將一個(gè)圖片以二進(jìn)制值的形式存入Xml文件中的實(shí)例代碼

    這篇文章介紹了將一個(gè)圖片以二進(jìn)制值的形式存入Xml文件中的實(shí)例代碼,有需要的朋友可以參考一下
    2013-07-07
  • Visual Studio 2017如何用正則修改部分內(nèi)容詳解

    Visual Studio 2017如何用正則修改部分內(nèi)容詳解

    這篇文章主要給大家介紹了關(guān)于Visual Studio 2017如何用正則修改部分內(nèi)容的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2018-05-05
  • Asp.Net Core輕松學(xué)之利用日志監(jiān)視進(jìn)行服務(wù)遙測(cè)詳解

    Asp.Net Core輕松學(xué)之利用日志監(jiān)視進(jìn)行服務(wù)遙測(cè)詳解

    這篇文章主要給大家介紹了關(guān)于Asp.Net Core輕松學(xué)之利用日志監(jiān)視進(jìn)行服務(wù)遙測(cè)的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起看看吧
    2018-12-12
  • 詳談.NET的異常處理

    詳談.NET的異常處理

    本文在對(duì)異常的介紹中,主要介紹了CLR的異常處理機(jī)制,一些較為通用的異常代碼,以及對(duì)Exception類的介紹。具有很好的參考價(jià)值,需要的朋友一起來看下吧
    2016-12-12
  • C#獲取當(dāng)前頁(yè)面的URL示例代碼

    C#獲取當(dāng)前頁(yè)面的URL示例代碼

    獲取當(dāng)前頁(yè)面的URL在某些情況下還是比較使用的,下面為大家介紹下如何通過C#以及Javascript獲取當(dāng)前頁(yè)面的URL,感興趣的朋友不要錯(cuò)過
    2013-11-11
  • LazyCaptcha自定義隨機(jī)驗(yàn)證碼和字體的示例詳解

    LazyCaptcha自定義隨機(jī)驗(yàn)證碼和字體的示例詳解

    LazyCaptcha是仿EasyCaptcha和SimpleCaptcha,基于.Net?Standard?2.1的圖形驗(yàn)證碼模塊,這篇文章主要介紹了LazyCaptcha自定義隨機(jī)驗(yàn)證碼和字體?,需要的朋友可以參考下
    2022-03-03
  • GridView_RowUpdating取不到新值的解決方法

    GridView_RowUpdating取不到新值的解決方法

    GridView_RowUpdating取不到新值的解決方法,需要的朋友可以參考一下
    2013-05-05

最新評(píng)論

庆城县| 黑龙江省| 德令哈市| 竹溪县| 九江县| 潼南县| 称多县| 精河县| 泗洪县| 淳安县| 濉溪县| 福清市| 长丰县| 濮阳县| 西昌市| 台山市| 东明县| 苍梧县| 凯里市| 大悟县| 泰州市| 天祝| 剑川县| 远安县| 扶余县| 武威市| 崇礼县| 乡宁县| 贵州省| 胶州市| 公主岭市| 天津市| 民勤县| 弥勒县| 灯塔市| 通山县| 岳普湖县| 阿克苏市| 府谷县| 湘西| 丰县|