首页 > 代码库 > 泛型的导入导出的公用方法
泛型的导入导出的公用方法
using NPOI.HSSF.UserModel;using NPOI.SS.Formula.Functions;using NPOI.SS.UserModel;using System;using System.Collections.Generic;using System.Data;using System.IO;using System.Linq;using System.Reflection;using System.Text;using System.Threading.Tasks;namespace Farinfo.Ethics.Common{ public class IntroductionAndExport<T> where T : class,new() { //导出 public static void RenderToExcel(IEnumerable<T> list,string title) { IWorkbook workbook = new HSSFWorkbook(); ISheet sheet = workbook.CreateSheet(); DirectoryInfo imagesfile = new DirectoryInfo(("d:/")); string strFileName = imagesfile.FullName.ToString(); int index = 0; //填充表头 IRow dataRow = sheet.CreateRow(0); foreach (PropertyInfo pi in list.FirstOrDefault().GetType().GetProperties()) { dataRow.CreateCell(index).SetCellValue(pi.Name); index++; } int id = 0; foreach (T model in list) { id = id + 1; IRow headerRow = sheet.CreateRow(id); PropertyInfo[] proList = model.GetType().GetProperties(); for (int i = 0; i < proList.Count(); i++) { var name = proList[i].GetValue(model, null); if (name == null) headerRow.CreateCell(i).SetCellValue(""); else headerRow.CreateCell(i).SetCellValue(name.ToString()); } } //保存 using (MemoryStream ms = new MemoryStream()) { workbook.Write(ms); File.Create(strFileName + title + ".xls").Close(); using (FileStream fs = new FileStream(strFileName + DateTime.Now.Second + ".xls", FileMode.Create, FileAccess.Write)) { byte[] data = http://www.mamicode.com/ms.ToArray();"Mark") { if (int.TryParse(cell.StringCellValue, out num)) { model.GetType().GetProperties()[j].SetValue(model, num, null); } else if (Guid.TryParse(cell.StringCellValue, out id)) { model.GetType().GetProperties()[j].SetValue(model, id, null); } else if (DateTime.TryParse(cell.StringCellValue, out time)) { model.GetType().GetProperties()[j].SetValue(model, time, null); } else if (cell.StringCellValue =http://www.mamicode.com/="") { model.GetType().GetProperties()[j].SetValue(model, null, null); } else { model.GetType().GetProperties()[j].SetValue(model, cell.StringCellValue, null); } } } list.Add(model); } } } }}
泛型的导入导出的公用方法
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。