using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using System.Web; using NPOI.HPSF; using System.Data; namespace Mmmis.Common { public class ExcelHelper { #region Excel导入 /// <summary> /// 从Excel取数据并记录到List集合里 /// </summary> /// <param name="cellHeard">单元头的值和名称:{ { "UserName", "姓名" }, { "Age", "年龄" } };</param> /// <param name="filePath">保存文件绝对路径</param> /// <param name="errorMsg">错误信息</param> /// <returns>转换后的List对象集合</returns> public static List<T> ExcelToEntityList<T>(Dictionary<string, string> cellHeard, string filePath, out StringBuilder errorMsg) where T : new() { List<T> enlist = new List<T>(); errorMsg = new StringBuilder(); try { if (Regex.IsMatch(filePath, ".xls$")) // 2003 { enlist = Excel2003ToEntityList<T>(cellHeard, filePath, out errorMsg); } else if (Regex.IsMatch(filePath, ".xlsx$")) // 2007 { //return FailureResultMsg("请选择Excel文件"); // 未设计 } return enlist; } catch (Exception ex) { throw ex; } } /// <summary> /// 从Excel2003取数据并记录到List集合里 /// </summary> /// <param name="cellHeard">单元头的Key和Value:{ { "UserName", "姓名" }, { "Age", "年龄" } };</param> /// <param name="filePath">保存文件绝对路径</param> /// <param name="errorMsg">错误信息</param> /// <returns>转换好的List对象集合</returns> private static List<T> Excel2003ToEntityList<T>(Dictionary<string, string> cellHeard, string filePath, out StringBuilder errorMsg) where T : new() { errorMsg = new StringBuilder(); // 错误信息,Excel转换到实体对象时,会有格式的错误信息 List<T> enlist = new List<T>(); // 转换后的集合 List<string> keys = cellHeard.Keys.ToList(); // 要赋值的实体对象属性名称 try { using (FileStream fs = File.OpenRead(filePath)) { HSSFWorkbook workbook = new HSSFWorkbook(fs); HSSFSheet sheet = (HSSFSheet)workbook.GetSheetAt(0); // 获取此文件第一个Sheet页 for (int i = 1; i <= sheet.LastRowNum; i++) // 从1开始,第0行为单元头 { // 1.判断当前行是否空行,若空行就不在进行读取下一行操作,结束Excel读取操作 if (sheet.GetRow(i) == null) { break; } T en = new T(); string errStr = ""; // 当前行转换时,是否有错误信息,格式为:第1行数据转换异常:XXX列; for (int j = 0; j < keys.Count; j++) { // 2.若属性头的名称包含'.',就表示是子类里的属性,那么就要遍历子类,eg:UserEn.TrueName if (keys[j].IndexOf(".") >= 0) { // 2.1解析子类属性 string[] properotyArray = keys[j].Split(new string[] { "." }, StringSplitOptions.RemoveEmptyEntries); string subClassName = properotyArray[0]; // '.'前面的为子类的名称 string subClassProperotyName = properotyArray[1]; // '.'后面的为子类的属性名称 System.Reflection.PropertyInfo subClassInfo = en.GetType().GetProperty(subClassName); // 获取子类的类型 if (subClassInfo != null) { // 2.1.1 获取子类的实例 var subClassEn = en.GetType().GetProperty(subClassName).GetValue(en, null); // 2.1.2 根据属性名称获取子类里的属性信息 System.Reflection.PropertyInfo properotyInfo = subClassInfo.PropertyType.GetProperty(subClassProperotyName); if (properotyInfo != null) { try { // Excel单元格的值转换为对象属性的值,若类型不对,记录出错信息 properotyInfo.SetValue(subClassEn, GetExcelCellToProperty(properotyInfo.PropertyType, sheet.GetRow(i).GetCell(j)), null); } catch (Exception e) { if (errStr.Length == 0) { errStr = "第" + i + "行数据转换异常:"; } errStr += cellHeard[keys[j]] + "列;"; } } } } else { // 3.给指定的属性赋值 System.Reflection.PropertyInfo properotyInfo = en.GetType().GetProperty(keys[j]); if (properotyInfo != null) { try { // Excel单元格的值转换为对象属性的值,若类型不对,记录出错信息 properotyInfo.SetValue(en, GetExcelCellToProperty(properotyInfo.PropertyType, sheet.GetRow(i).GetCell(j)), null); } catch (Exception e) { if (errStr.Length == 0) { errStr = "第" + i + "行数据转换异常:"; } errStr += cellHeard[keys[j]] + "列;"; } } } } // 若有错误信息,就添加到错误信息里 if (errStr.Length > 0) { errorMsg.AppendLine(errStr); } enlist.Add(en); } } return enlist; } catch (Exception ex) { throw ex; } } #endregion Excel导入 #region Excel导出 /// <summary> /// 实体类集合导出到EXCLE2003 /// </summary> /// <param name="cellHeard">单元头的Key和Value:{ { "UserName", "姓名" }, { "Age", "年龄" } };</param> /// <param name="enList">数据源</param> /// <param name="sheetName">工作表名称</param> /// <returns>文件的下载地址</returns> public static string EntityListToExcel2003(Dictionary<string, string> cellHeard, IList enList, string sheetName) { try { string fileName = sheetName + ".xls"; // 文件名称 string urlPath = "xjgl/uploadfiles/ExcelFiles/" + fileName; // 文件下载的URL地址,供给前台下载 string filePath = HttpContext.Current.Server.MapPath(urlPath); // 文件路径 // 1.检测是否存在文件夹,若不存在就建立个文件夹 string directoryName = Path.GetDirectoryName(filePath); if (!Directory.Exists(directoryName)) { Directory.CreateDirectory(directoryName); } // 2.解析单元格头部,设置单元头的中文名称 HSSFWorkbook workbook = new HSSFWorkbook(); // 工作簿 ISheet sheet = workbook.CreateSheet(sheetName); // 工作表 IRow row = sheet.CreateRow(0); List<string> keys = cellHeard.Keys.ToList(); for (int i = 0; i < keys.Count; i++) { row.CreateCell(i).SetCellValue(cellHeard[keys[i]]); // 列名为Key的值 } // 3.List对象的值赋值到Excel的单元格里 int rowIndex = 1; // 从第二行开始赋值(第一行已设置为单元头) foreach (var en in enList) { IRow rowTmp = sheet.CreateRow(rowIndex); for (int i = 0; i < keys.Count; i++) // 根据指定的属性名称,获取对象指定属性的值 { string cellValue = ""; // 单元格的值 object properotyValue = null; // 属性的值 System.Reflection.PropertyInfo properotyInfo = null; // 属性的信息 // 3.1 若属性头的名称包含'.',就表示是子类里的属性,那么就要遍历子类,eg:UserEn.UserName if (keys[i].IndexOf(".") >= 0) { // 3.1.1 解析子类属性(这里只解析1层子类,多层子类未处理) string[] properotyArray = keys[i].Split(new string[] { "." }, StringSplitOptions.RemoveEmptyEntries); string subClassName = properotyArray[0]; // '.'前面的为子类的名称 string subClassProperotyName = properotyArray[1]; // '.'后面的为子类的属性名称 System.Reflection.PropertyInfo subClassInfo = en.GetType().GetProperty(subClassName); // 获取子类的类型 if (subClassInfo != null) { // 3.1.2 获取子类的实例 var subClassEn = en.GetType().GetProperty(subClassName).GetValue(en, null); // 3.1.3 根据属性名称获取子类里的属性类型 properotyInfo = subClassInfo.PropertyType.GetProperty(subClassProperotyName); if (properotyInfo != null) { properotyValue = properotyInfo.GetValue(subClassEn, null); // 获取子类属性的值 } } } else { // 3.2 若不是子类的属性,直接根据属性名称获取对象对应的属性 properotyInfo = en.GetType().GetProperty(keys[i]); if (properotyInfo != null) { properotyValue = properotyInfo.GetValue(en, null); } } // 3.3 属性值经过转换赋值给单元格值 if (properotyValue != null) { cellValue = properotyValue.ToString(); // 3.3.1 对时间初始值赋值为空 if (cellValue.Trim() == "0001/1/1 0:00:00" || cellValue.Trim() == "0001/1/1 23:59:59") { cellValue = ""; } } // 3.4 填充到Excel的单元格里 rowTmp.CreateCell(i).SetCellValue(cellValue); } rowIndex++; } // 4.生成文件 FileStream file = new FileStream(filePath, FileMode.Create); workbook.Write(file); file.Close(); // 5.返回下载路径 return urlPath; } catch (Exception ex) { throw ex; } } /// <summary> /// 导出到Excel表(一层属性) /// </summary> /// <param name="cellHeard">单元头的Key和Value:{ { "UserName", "姓名" }, { "Age", "年龄" } }</param> /// <param name="enList">数据源LIST</param> /// <param name="sheetName">工作表名称</param> /// <returns>文件的下载地址</returns> public static string EntityListToExcel2003One(Dictionary<string, string> cellHeard, IList enList, string sheetName) { try { string fileName = sheetName + ".xls"; // 文件名称 string urlPath = "xjgl/uploadfiles/ExcelFiles/" + fileName; // 文件下载的URL地址,供给前台下载 string filePath = HttpContext.Current.Server.MapPath(urlPath); // 文件路径 string directoryName = Path.GetDirectoryName(filePath); if (!Directory.Exists(directoryName)) Directory.CreateDirectory(directoryName); HSSFWorkbook workbook = new HSSFWorkbook(); // 工作簿 ISheet sheet = workbook.CreateSheet(sheetName); // 工作表 IRow row = sheet.CreateRow(0); List<string> keys = cellHeard.Keys.ToList(); for (int i = 0; i < keys.Count; i++) row.CreateCell(i).SetCellValue(cellHeard[keys[i]]); // 列名为Key的值 int rowIndex = 1; // 从第二行开始赋值(第一行已设置为单元头) foreach (var en in enList) { IRow rowTmp = sheet.CreateRow(rowIndex); for (int i = 0; i < keys.Count; i++) // 根据指定的属性名称,获取对象指定属性的值 { string cellValue = ""; // 单元格的值 object properotyValue = null; // 属性的值 System.Reflection.PropertyInfo properotyInfo = null; // 属性的信息 properotyInfo = en.GetType().GetProperty(keys[i]); if (properotyInfo != null) properotyValue = properotyInfo.GetValue(en, null); if (properotyValue != null) cellValue = properotyValue.ToString(); rowTmp.CreateCell(i).SetCellValue(cellValue); } rowIndex++; } FileStream file = new FileStream(filePath, FileMode.Create); workbook.Write(file); file.Close(); return urlPath; } catch (Exception ex) { throw ex; } } #endregion Excel导出 /// <summary> /// 保存Excel文件 /// <para>Excel的导入导出都会在服务器生成一个文件</para> /// <para>路径:UpFiles/ExcelFiles</para> /// </summary> /// <param name="file">传入的文件对象</param> /// <returns>如果保存成功则返回文件的位置;如果保存失败则返回空</returns> public static string SaveExcelFile(HttpPostedFile file) { try { var fileName = file.FileName.Insert(file.FileName.LastIndexOf('.'), "-" + DateTime.Now.ToString("yyyyMMddHHmmssfff")); var filePath = Path.Combine(HttpContext.Current.Server.MapPath("~/UpFiles/ExcelFiles"), fileName); string directoryName = Path.GetDirectoryName(filePath); if (!Directory.Exists(directoryName)) { Directory.CreateDirectory(directoryName); } file.SaveAs(filePath); return filePath; } catch { return string.Empty; } } /// <summary> /// 从Excel获取值传递到对象的属性里 /// </summary> /// <param name="distanceType">目标对象类型</param> /// <param name="sourceCell">对象属性的值</param> private static Object GetExcelCellToProperty(Type distanceType, ICell sourceCell) { object rs = distanceType.IsValueType ? Activator.CreateInstance(distanceType) : null; // 1.判断传递的单元格是否为空 if (sourceCell == null || string.IsNullOrEmpty(sourceCell.ToString())) { return rs; } // 2.Excel文本和数字单元格转换,在Excel里文本和数字是不能进行转换,所以这里预先存值 object sourceValue = null; switch (sourceCell.CellType) { case CellType.Blank: break; case CellType.Boolean: break; case CellType.Error: break; case CellType.Formula: break; case CellType.Numeric: sourceValue = sourceCell.NumericCellValue; break; case CellType.String: sourceValue = sourceCell.StringCellValue; break; case CellType.Unknown: break; default: break; } string valueDataType = distanceType.Name; // 在这里进行特定类型的处理 switch (valueDataType.ToLower()) // 以防出错,全部小写 { case "string": rs = sourceValue.ToString(); break; case "int": case "int16": case "int32": rs = (int)Convert.ChangeType(sourceCell.NumericCellValue.ToString(), distanceType); break; case "float": case "single": rs = (float)Convert.ChangeType(sourceCell.NumericCellValue.ToString(), distanceType); break; case "datetime": rs = sourceCell.DateCellValue; break; case "guid": rs = (Guid)Convert.ChangeType(sourceCell.NumericCellValue.ToString(), distanceType); return rs; } return rs; } public static string EntityListToExcel2003Dt(Dictionary<string, string> cellHeard, DataTable enList, string sheetName) { try { string fileName = sheetName + ".xls"; // 文件名称 string urlPath = "xjgl/uploadfiles/ExcelFiles/" + fileName; // 文件下载的URL地址,供给前台下载 string filePath = HttpContext.Current.Server.MapPath(urlPath); // 文件路径 // 1.检测是否存在文件夹,若不存在就建立个文件夹 string directoryName = Path.GetDirectoryName(filePath); if (!Directory.Exists(directoryName)) { Directory.CreateDirectory(directoryName); } // 2.解析单元格头部,设置单元头的中文名称 HSSFWorkbook workbook = new HSSFWorkbook(); // 工作簿 ISheet sheet = workbook.CreateSheet(sheetName); // 工作表 IRow row = sheet.CreateRow(0); List<string> keys = cellHeard.Keys.ToList(); for (int i = 0; i < keys.Count; i++) { row.CreateCell(i).SetCellValue(cellHeard[keys[i]]); // 列名为Key的值 } // 3.List对象的值赋值到Excel的单元格里 int rowIndex = 1; // 从第二行开始赋值(第一行已设置为单元头) foreach (var en in enList.Rows) { IRow rowTmp = sheet.CreateRow(rowIndex); for (int i = 0; i < keys.Count; i++) // 根据指定的属性名称,获取对象指定属性的值 { string cellValue = ""; // 单元格的值 object properotyValue = null; // 属性的值 System.Reflection.PropertyInfo properotyInfo = null; // 属性的信息 // 3.1 若属性头的名称包含'.',就表示是子类里的属性,那么就要遍历子类,eg:UserEn.UserName if (keys[i].IndexOf(".") >= 0) { // 3.1.1 解析子类属性(这里只解析1层子类,多层子类未处理) string[] properotyArray = keys[i].Split(new string[] { "." }, StringSplitOptions.RemoveEmptyEntries); string subClassName = properotyArray[0]; // '.'前面的为子类的名称 string subClassProperotyName = properotyArray[1]; // '.'后面的为子类的属性名称 System.Reflection.PropertyInfo subClassInfo = en.GetType().GetProperty(subClassName); // 获取子类的类型 if (subClassInfo != null) { // 3.1.2 获取子类的实例 var subClassEn = en.GetType().GetProperty(subClassName).GetValue(en, null); // 3.1.3 根据属性名称获取子类里的属性类型 properotyInfo = subClassInfo.PropertyType.GetProperty(subClassProperotyName); if (properotyInfo != null) { properotyValue = properotyInfo.GetValue(subClassEn, null); // 获取子类属性的值 } } } else { // 3.2 若不是子类的属性,直接根据属性名称获取对象对应的属性 properotyInfo = en.GetType().GetProperty(keys[i]); if (properotyInfo != null) { properotyValue = properotyInfo.GetValue(en, null); } } // 3.3 属性值经过转换赋值给单元格值 if (properotyValue != null) { cellValue = properotyValue.ToString(); // 3.3.1 对时间初始值赋值为空 if (cellValue.Trim() == "0001/1/1 0:00:00" || cellValue.Trim() == "0001/1/1 23:59:59") { cellValue = ""; } } // 3.4 填充到Excel的单元格里 rowTmp.CreateCell(i).SetCellValue(cellValue); } rowIndex++; } // 4.生成文件 FileStream file = new FileStream(filePath, FileMode.Create); workbook.Write(file); file.Close(); // 5.返回下载路径 return urlPath; } catch (Exception ex) { throw ex; } } public static string EntityListToExcel2003(Dictionary<string, string> cellHeard, DataTable dt, string sheetName) { try { string fileName = sheetName + "-" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".xls"; // 文件名称 string urlPath = "xjgl/uploadfiles/ExcelFiles/" + fileName; // 文件下载的URL地址,供给前台下载 string filePath = HttpContext.Current.Server.MapPath(urlPath); // 文件路径 // 1.检测是否存在文件夹,若不存在就建立个文件夹 string directoryName = Path.GetDirectoryName(filePath); if (!Directory.Exists(directoryName)) { Directory.CreateDirectory(directoryName); } // 2.解析单元格头部,设置单元头的中文名称 HSSFWorkbook workbook = new HSSFWorkbook(); // 工作簿 ISheet sheet = workbook.CreateSheet(sheetName); // 工作表 IRow row = sheet.CreateRow(0); List<string> keys = cellHeard.Keys.ToList(); for (int i = 0; i < keys.Count; i++) { row.CreateCell(i).SetCellValue(cellHeard[keys[i]]); // 列名为Key的值 } // 3.List对象的值赋值到Excel的单元格里 int rowIndex = 1; // 从第二行开始赋值(第一行已设置为单元头) for (int j = 0; j < dt.Columns.Count; j++) { for (int i = 0; i < dt.Rows.Count; i++) { string cellValue = ""; // 单元格的值 IRow rowTmp = sheet.CreateRow(i); cellValue = dt.Rows[i][j].ToString(); rowTmp.CreateCell(i).SetCellValue(cellValue); } } // 4.生成文件 FileStream file = new FileStream(filePath, FileMode.Create); workbook.Write(file); file.Close(); // 5.返回下载路径 return urlPath; } catch (Exception ex) { throw ex; } } HSSFWorkbook hssfworkbook; #region /// <summary> /// 导入Excel转datatable /// </summary> /// <param name="filePath"></param> /// <returns></returns> public DataTable ImportExcelFile(string filePath) { #region//初始化信息 try { using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read)) { hssfworkbook = new HSSFWorkbook(file); } } catch (Exception e) { throw e; } #endregion NPOI.SS.UserModel.ISheet sheet = hssfworkbook.GetSheetAt(0); System.Collections.IEnumerator rows = sheet.GetRowEnumerator(); DataTable dt = new DataTable(); for (int j = 0; j < (sheet.GetRow(0).LastCellNum); j++) { dt.Columns.Add(Convert.ToChar(((int)'A') + j).ToString()); } while (rows.MoveNext()) { HSSFRow row = (HSSFRow)rows.Current; DataRow dr = dt.NewRow(); for (int i = 0; i < row.LastCellNum; i++) { NPOI.SS.UserModel.ICell cell = row.GetCell(i); if (cell == null) { dr[i] = null; } else { dr[i] = cell.ToString(); } } dt.Rows.Add(dr); } return dt; } #endregion /// <summary> /// Datatable转Excel表 /// </summary> /// <param name="dt"></param> /// <param name="filePath"></param> public static void WriteExcel(DataTable dt, string filePath) { if (!string.IsNullOrEmpty(filePath) && null != dt && dt.Rows.Count > 0) { NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook(); NPOI.SS.UserModel.ISheet sheet = book.CreateSheet(dt.TableName); NPOI.SS.UserModel.IRow row = sheet.CreateRow(0); for (int i = 0; i < dt.Columns.Count; i++) { row.CreateCell(i).SetCellValue(dt.Columns[i].ColumnName); } for (int i = 0; i < dt.Rows.Count; i++) { NPOI.SS.UserModel.IRow row2 = sheet.CreateRow(i + 1); for (int j = 0; j < dt.Columns.Count; j++) { row2.CreateCell(j).SetCellValue(Convert.ToString(dt.Rows[i][j])); } } // 写入到客户端 using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { book.Write(ms); using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write)) { byte[] data = ms.ToArray(); fs.Write(data, 0, data.Length); fs.Flush(); } book = null; } } } /// <summary> /// 导入数据超过60000条新增sheet /// </summary> /// <param name="dt"></param> /// <param name="filePath"></param> public static void NpoiExcel(DataTable dt, string filePath) { NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook(); int SheetNum = 1; int tempIndex = 1; //标示 NPOI.SS.UserModel.ISheet sheet = book.CreateSheet("Sheet" + SheetNum); NPOI.SS.UserModel.IRow headerrow = sheet.CreateRow(0); ICellStyle style = book.CreateCellStyle(); style.Alignment = HorizontalAlignment.Center; style.VerticalAlignment = VerticalAlignment.Center; for (int i = 0; i < dt.Columns.Count; i++) { ICell cell = headerrow.CreateCell(i); cell.CellStyle = style; cell.SetCellValue(dt.Columns[i].ColumnName); } //数据 for (int i = 0; i < dt.Rows.Count; i++) { IRow row1 = sheet.CreateRow(tempIndex); for (int j = 0; j < dt.Columns.Count; j++) { ICell cell = row1.CreateCell(j); cell.SetCellValue(dt.Rows[i][j].ToString()); } if (tempIndex == 60000) { SheetNum++; sheet = book.CreateSheet("Sheet" + SheetNum);// tempIndex = 0; headerrow = sheet.CreateRow(0); style = book.CreateCellStyle(); style.Alignment = HorizontalAlignment.Center; style.VerticalAlignment = VerticalAlignment.Center; for (int m = 0; m < dt.Columns.Count; m++) { ICell cell = headerrow.CreateCell(m); cell.CellStyle = style; cell.SetCellValue(dt.Columns[m].ColumnName); } } tempIndex++; } using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { book.Write(ms); using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write)) { byte[] data = ms.ToArray(); fs.Write(data, 0, data.Length); fs.Flush(); } book = null; } } public static void WriteExcelMore(DataTable dt, string filePath) { if (!string.IsNullOrEmpty(filePath) && null != dt && dt.Rows.Count > 0) { NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook(); NPOI.SS.UserModel.ISheet sheet = null; NPOI.SS.UserModel.IRow row = null; NPOI.SS.UserModel.IRow row2 = null; for (int kk = 1; kk < (dt.Rows.Count / 60000) + 2; kk++) { book.CreateSheet(dt.TableName + kk.ToString()); row = sheet.CreateRow(0); for (int i = 0; i < dt.Columns.Count; i++) { row.CreateCell(i).SetCellValue(dt.Columns[i].ColumnName); } for (int i = (kk - 1) * 60000; i < (dt.Rows.Count - ((kk - 1) * 60000)); i++) { row2 = sheet.CreateRow(i + 1); for (int j = 0; j < dt.Columns.Count; j++) { row2.CreateCell(j).SetCellValue(Convert.ToString(dt.Rows[i][j])); } } } // 写入到客户端 using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { book.Write(ms); using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write)) { byte[] data = ms.ToArray(); fs.Write(data, 0, data.Length); fs.Flush(); } book = null; } } } public static string EntityListToExcel2003More(Dictionary<string, string> cellHeard, IList enList, string sheetName) { try { string fileName = sheetName + ".xls"; // 文件名称 string urlPath = "xjgl/uploadfiles/ExcelFiles/" + fileName; // 文件下载的URL地址,供给前台下载 string filePath = HttpContext.Current.Server.MapPath(urlPath); // 文件路径 // 1.检测是否存在文件夹,若不存在就建立个文件夹 string directoryName = Path.GetDirectoryName(filePath); if (!Directory.Exists(directoryName)) { Directory.CreateDirectory(directoryName); } int SheetNum = 1; //标示 // 2.解析单元格头部,设置单元头的中文名称 HSSFWorkbook workbook = new HSSFWorkbook(); // 工作簿 ISheet sheet = workbook.CreateSheet("Sheet" + SheetNum.ToString()); // 工作表 IRow row = sheet.CreateRow(0); List<string> keys = cellHeard.Keys.ToList(); for (int i = 0; i < keys.Count; i++) { row.CreateCell(i).SetCellValue(cellHeard[keys[i]]); // 列名为Key的值 } // 3.List对象的值赋值到Excel的单元格里 int rowIndex = 1; // 从第二行开始赋值(第一行已设置为单元头) foreach (var en in enList) { IRow rowTmp = sheet.CreateRow(rowIndex); for (int i = 0; i < keys.Count; i++) // 根据指定的属性名称,获取对象指定属性的值 { string cellValue = ""; // 单元格的值 object properotyValue = null; // 属性的值 System.Reflection.PropertyInfo properotyInfo = null; // 属性的信息 // 3.1 若属性头的名称包含'.',就表示是子类里的属性,那么就要遍历子类,eg:UserEn.UserName if (keys[i].IndexOf(".") >= 0) { // 3.1.1 解析子类属性(这里只解析1层子类,多层子类未处理) string[] properotyArray = keys[i].Split(new string[] { "." }, StringSplitOptions.RemoveEmptyEntries); string subClassName = properotyArray[0]; // '.'前面的为子类的名称 string subClassProperotyName = properotyArray[1]; // '.'后面的为子类的属性名称 System.Reflection.PropertyInfo subClassInfo = en.GetType().GetProperty(subClassName); // 获取子类的类型 if (subClassInfo != null) { // 3.1.2 获取子类的实例 var subClassEn = en.GetType().GetProperty(subClassName).GetValue(en, null); // 3.1.3 根据属性名称获取子类里的属性类型 properotyInfo = subClassInfo.PropertyType.GetProperty(subClassProperotyName); if (properotyInfo != null) { properotyValue = properotyInfo.GetValue(subClassEn, null); // 获取子类属性的值 } } } else { // 3.2 若不是子类的属性,直接根据属性名称获取对象对应的属性 properotyInfo = en.GetType().GetProperty(keys[i]); if (properotyInfo != null) { properotyValue = properotyInfo.GetValue(en, null); } } // 3.3 属性值经过转换赋值给单元格值 if (properotyValue != null) { cellValue = properotyValue.ToString(); // 3.3.1 对时间初始值赋值为空 if (cellValue.Trim() == "0001/1/1 0:00:00" || cellValue.Trim() == "0001/1/1 23:59:59") { cellValue = ""; } } // 3.4 填充到Excel的单元格里 rowTmp.CreateCell(i).SetCellValue(cellValue); } if (rowIndex == 60000) { SheetNum++; rowIndex = 0; sheet = workbook.CreateSheet("Sheet" + SheetNum.ToString()); row = sheet.CreateRow(0); List<string> keyss = cellHeard.Keys.ToList(); for (int ii = 0; ii < keyss.Count; ii++) { row.CreateCell(ii).SetCellValue(cellHeard[keys[ii]]); // 列名为Key的值 } } rowIndex++; } // 4.生成文件 FileStream file = new FileStream(filePath, FileMode.Create); workbook.Write(file); file.Close(); // 5.返回下载路径 return urlPath; } catch (Exception ex) { throw ex; } } } }
调用:
private void lnkToExcel_Click(object sender, System.EventArgs e) { DataTable dt = SqlData.ExecuteDataset(DbConfig.GetSetting(), CommandType.Text, BuildSQL()).Tables[0]; List<Common.exp> enlist = new List<Common.exp>(); enlist = GetList<Common.exp>(dt); Dictionary<string, string> cellheader = new Dictionary<string, string>(); for (int i = 0; i < dt.Columns.Count; i++) { cellheader.Add(dt.Columns[i].ToString(), dt.Columns[i].ToString()); } string urlPath = ""; if (dt.Rows.Count > 60000) urlPath = Gmis.Common.ExcelHelper.EntityListToExcel2003More(cellheader, enlist, "xjexp"); else urlPath = Gmis.Common.ExcelHelper.EntityListToExcel2003One(cellheader, enlist, "xjexp"); DownFile(this, Server.MapPath(urlPath), "exp", false, true); }
public void DownFile(Page page, string path, string downfilename, bool isviture = true, bool deletefile = false) { string sFileName = ""; if (isviture) { sFileName = page.Server.MapPath(path); } else { sFileName = path; } string type = Path.GetExtension(sFileName); FileStream fileStream = new FileStream(sFileName, FileMode.Open); long fileSize = fileStream.Length; byte[] fileBuffer = new byte[fileSize]; fileStream.Read(fileBuffer, 0, (int)fileSize); //如果不写fileStream.Close()语句,用户在下载过程中选择取消,将不能再次下载 fileStream.Close(); page.Response.ContentType = "application/octet-stream"; page.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(downfilename + type, Encoding.UTF8)); page.Response.AddHeader("Content-Length", fileSize.ToString()); page.Response.BinaryWrite(fileBuffer); if (deletefile) { System.IO.File.Delete(sFileName); } page.Response.End(); page.Response.Close(); }
/// <summary> /// DataTable转换成List<T> /// </summary> /// <typeparam name="T"></typeparam> /// <param name="table"></param> /// <returns></returns> public static List<T> GetList<T>(DataTable table) { List<T> list = new List<T>(); T t = default(T); PropertyInfo[] propertypes = null; string tempName = string.Empty; foreach (DataRow row in table.Rows) { t = Activator.CreateInstance<T>(); propertypes = t.GetType().GetProperties(); foreach (PropertyInfo pro in propertypes) { tempName = pro.Name; if (table.Columns.Contains(tempName)) { object value = row[tempName]; if (!value.ToString().Equals("")) { pro.SetValue(t, value, null); } } } list.Add(t); } return list.Count == 0 ? null : list; } /// <summary> /// List<T>转换成DataTable /// </summary> /// <typeparam name="T"></typeparam> /// <param name="list"></param> /// <returns></returns> public static DataSet ConvertToDataSet<T>(IList<T> list) { if (list == null || list.Count <= 0) { return null; } DataSet ds = new DataSet(); DataTable dt = new DataTable(typeof(T).Name); DataColumn column; DataRow row; System.Reflection.PropertyInfo[] myPropertyInfo = typeof(T).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance); foreach (T t in list) { if (t == null) { continue; } row = dt.NewRow(); for (int i = 0, j = myPropertyInfo.Length; i < j; i++) { System.Reflection.PropertyInfo pi = myPropertyInfo[i]; string name = pi.Name; if (dt.Columns[name] == null) { column = new DataColumn(name, pi.PropertyType); dt.Columns.Add(column); } row[name] = pi.GetValue(t, null); } dt.Rows.Add(row); } ds.Tables.Add(dt); return ds; }
下载源码 http://download.csdn.net/download/u012949335/10150996