This article is a mirror article of machine translation, please click here to jump to the original article.

View: 14471|Reply: 0

[ASP.NET] asp.net MVC exports the List collection or Datatable to an Excel table

[Copy link]
Posted on 11/13/2015 10:19:13 AM | | |
  1. /// <summary>
  2.     /// 将DataTable导出成Excel表格
  3.     /// </summary>
  4.     public class ExcelHelper
  5.     {
  6.         public MemoryStream RenderToExcel(DataTable table)
  7.         {
  8.             MemoryStream ms = new MemoryStream();

  9.             using (table)
  10.             {
  11.                 IWorkbook workbook = new HSSFWorkbook();

  12.                 ISheet sheet = workbook.CreateSheet();

  13.                 IRow headerRow = sheet.CreateRow(0);

  14.                 // handling header.
  15.                 foreach (DataColumn column in table.Columns)
  16.                     headerRow.CreateCell(column.Ordinal).SetCellValue(column.Caption);//If Caption not set, returns the ColumnName value

  17.                 // handling value.
  18.                 int rowIndex = 1;

  19.                 foreach (DataRow row in table.Rows)
  20.                 {
  21.                     IRow dataRow = sheet.CreateRow(rowIndex);

  22.                     foreach (DataColumn column in table.Columns)
  23.                     {
  24.                         dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());
  25.                     }

  26.                     rowIndex++;
  27.                 }

  28.                 workbook.Write(ms);
  29.                 ms.Flush();
  30.                 ms.Position = 0;


  31.             }
  32.             return ms;
  33.         }
  34.     }
Copy code
  1. public ActionResult ExportBrand(int id)
  2.         {
  3.             int aaa = id;
  4.             //查询参加会议的数据
  5.             List<BLL.Entitys.InBoardRoomPersonnel> list = BLL.Brand.Index.GetJoinBrandUser(id);
  6.             //需要填写的字段
  7.             //List<BLL.Entitys.GetDictionary> dic = BLL.Until.GetUserInfo.SelectUser(Extcredits);
  8.             //转换成list集合
  9.             List<BLL.Entitys.UserInfo> userlist = new List<UserInfo>();
  10.             foreach (BLL.Entitys.InBoardRoomPersonnel ir in list)
  11.             {
  12.                 var getMS = new MemoryStream(ir.BoardRoomUser);
  13.                 getMS.Position = 0;
  14.                 BLL.Entitys.UserInfo u = BinarySerializerHelper.DeSerialize<BLL.Entitys.UserInfo>(getMS);
  15.                 userlist.Add(u);
  16.             }
  17.             DataTable dt = userlist.FillDataTable<BLL.Entitys.UserInfo>();
  18.             dt =BLL.Until.DataTableExtensions.TranslateDataTable(dt);
  19.             BLL.Until.ExcelHelper helper = new ExcelHelper();
  20.             //bll helper = new BLL.Export.ExportHelper();
  21.             MemoryStream ms = helper.RenderToExcel(dt);
  22.             return File(ms, "xls", "Brand" + DateTime.Now.ToString("yyyyMMddhhmm") + ".xls");
  23.         }
Copy code
  1. /// <summary>
  2.         /// 实体类转换成DataTable
  3.         /// </summary>
  4.         /// <param name="modelList">实体类列表</param>
  5.         /// <returns></returns>
  6.         public static DataTable FillDataTable<T>(this List<T> modelList)
  7.         {
  8.             if (modelList == null || modelList.Count == 0)
  9.             {
  10.                 return null;
  11.             }
  12.             DataTable dt = CreateData(modelList[0]);

  13.             foreach (T model in modelList)
  14.             {
  15.                 DataRow dataRow = dt.NewRow();
  16.                 foreach (PropertyInfo propertyInfo in typeof(T).GetProperties())
  17.                 {
  18.                     dataRow[propertyInfo.Name] = propertyInfo.GetValue(model, null);
  19.                 }
  20.                 dt.Rows.Add(dataRow);
  21.             }
  22.             return dt;
  23.         }

  24.         /// <summary>
  25.         /// 根据实体类得到表结构
  26.         /// </summary>
  27.         /// <param name="model">实体类</param>
  28.         /// <returns></returns>
  29.         private static DataTable CreateData<T>(T model)
  30.         {
  31.             DataTable dataTable = new DataTable(typeof(T).Name);
  32.             foreach (PropertyInfo propertyInfo in typeof(T).GetProperties())
  33.             {
  34.                 dataTable.Columns.Add(new DataColumn(propertyInfo.Name, propertyInfo.PropertyType));
  35.             }
  36.             return dataTable;
  37.         }
  38.         /// <summary>
  39.         /// DataTable字段翻译成中文
  40.         /// </summary>
  41.         /// <param name="table"></param>
  42.         /// <returns></returns>
  43.         public static DataTable TranslateDataTable(DataTable table)
  44.         {
  45.             DataTable dt = new DataTable();
  46.             dt.TableName = "TempTable";

  47.             if (table != null && table.Rows.Count > 0)
  48.             {
  49.                 //先为dt构造列信息  
  50.                 foreach (DataColumn column in table.Columns)
  51.                 {
  52.                     string name = BLL.Until.GetUserInfo.GetBewrite(column.ColumnName);
  53.                     dt.Columns.Add(name);
  54.                 }

  55.                 for (int i = 0; i < table.Rows.Count; i++)
  56.                 {
  57.                     DataRow NewRow = dt.NewRow();
  58.                     DataRow row = table.Rows[i];

  59.                     for (int j = 0; j < dt.Columns.Count; j++)
  60.                     {
  61.                         NewRow[j] = row[j].ToString();
  62.                     }

  63.                     dt.Rows.Add(NewRow);
  64.                 }
  65.             }
  66.             return dt;
  67.         }
Copy code


If it is a list collection, you need to convert it to datatable before exporting it.
NPOI.zip (553.95 KB, Number of downloads: 2, 售价: 2 粒MB)




Previous:Many websites in China are held by clientHold
Next:&quot;The ConnectionString property has not been initialized.&quot; error resolution
Disclaimer:
All software, programming materials or articles published by Code Farmer Network are only for learning and research purposes; The above content shall not be used for commercial or illegal purposes, otherwise, users shall bear all consequences. The information on this site comes from the Internet, and copyright disputes have nothing to do with this site. You must completely delete the above content from your computer within 24 hours of downloading. If you like the program, please support genuine software, purchase registration, and get better genuine services. If there is any infringement, please contact us by email.

Mail To:help@itsvse.com