Cet article est un article miroir de traduction automatique, veuillez cliquer ici pour accéder à l’article original.

Vue: 14471|Répondre: 0

[ASP.NET] asp.net MVC exporte la collection de listes ou Datatable vers une table Excel

[Copié le lien]
Publié sur 13/11/2015 10:19:13 | | |
  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.     }
Code de copie
  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.         }
Code de copie
  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.         }
Code de copie


Si c’est une collection de listes, il faut la convertir en datatable avant de l’exporter.
NPOI.zip (553.95 KB, Nombre de téléchargements: 2, 售价: 2 粒MB)




Précédent:De nombreux sites web en Chine sont détenus par clientHold
Prochain:« La propriété ConnectionString n’a pas été initialisée. » résolution d’erreur
Démenti:
Tous les logiciels, supports de programmation ou articles publiés par Code Farmer Network sont uniquement destinés à l’apprentissage et à la recherche ; Le contenu ci-dessus ne doit pas être utilisé à des fins commerciales ou illégales, sinon les utilisateurs assumeront toutes les conséquences. Les informations sur ce site proviennent d’Internet, et les litiges de droits d’auteur n’ont rien à voir avec ce site. Vous devez supprimer complètement le contenu ci-dessus de votre ordinateur dans les 24 heures suivant le téléchargement. Si vous aimez le programme, merci de soutenir un logiciel authentique, d’acheter l’immatriculation et d’obtenir de meilleurs services authentiques. En cas d’infraction, veuillez nous contacter par e-mail.

Mail To:help@itsvse.com