using NPOI.HSSF.UserModel; using NPOI.HSSF.Util; using NPOI.SS.UserModel; using NPOI.SS.Util; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.IO; using System.Reflection; using System.Text; using System.Web; using WX.CRM.Common; namespace WX.CRM.WebHelper { public class ExcelHelper { #region 只有一列的数据导出Excel public static Stream ExportListObjectToExcel(List obj, string fieldName, string sheetName, DataFormart func) { HSSFWorkbook workbook = new HSSFWorkbook(); MemoryStream ms = new MemoryStream(); // handling header. // handling value. int sheetSize = 65535; int sheetCout = (obj.Count / sheetSize) + 1;//获取一个工作簿中多少页 for (int i = 0; i < sheetCout; i++) { ISheet sheet = workbook.CreateSheet(sheetName + (i + 1)); IRow headerRow = sheet.CreateRow(0); headerRow.CreateCell(0).SetCellValue(fieldName); int rowIndex = 1; int mcount = (i + 1) * sheetSize > obj.Count ? obj.Count : (i + 1) * sheetSize; for (int m = (i * sheetSize); m < mcount; m++) { IRow dataRow = sheet.CreateRow(rowIndex); dataRow.CreateCell(0).SetCellValue(string.Format("{0}", obj[m])); rowIndex++; } } //foreach (object row in obj) //{ // IRow dataRow = sheet.CreateRow(rowIndex); // dataRow.CreateCell(0).SetCellValue(string.Format("{0}", row)); // rowIndex++; //} workbook.Write(ms); ms.Flush(); ms.Position = 0; workbook = null; return ms; } #endregion 只有一列的数据导出Excel #region List反射导出Excel /// /// List反射导出Excel /// /// /// 实体列表 /// 工作表名称 /// 一个工作簿的数据量(不能超过65536) /// 返回一个流 public static Stream ExportListModelToExcel(List listModel, string sheetName, int sheetSize, DataFormart func) { HSSFWorkbook workbook = new HSSFWorkbook(); MemoryStream ms = new MemoryStream(); string columnName = string.Empty; int x = 0; DisplayNameAttribute attribute = null; if (sheetSize > 65536) sheetSize = 65536; int sheetCout = (listModel.Count / sheetSize) + 1;//获取一个工作簿中多少页 for (int i = 0; i < sheetCout; i++) { ISheet sheet = workbook.CreateSheet(sheetName + (i + 1)); IRow headerRow = sheet.CreateRow(0); // 设置表头. x = 0; foreach (PropertyInfo info in typeof(T).GetProperties()) { attribute = (DisplayNameAttribute)Attribute.GetCustomAttribute(info, typeof(DisplayNameAttribute)); headerRow.CreateCell(x).SetCellValue(attribute == null ? info.Name : attribute.DisplayName);//获取类中的DisplayName属性 x++; } // 绑定值 int rowIndex = 1; int mcount = (i + 1) * sheetSize > listModel.Count ? listModel.Count : (i + 1) * sheetSize; for (int m = (i * sheetSize); m < mcount; m++) { x = 0; IRow dataRow = sheet.CreateRow(rowIndex); foreach (PropertyInfo column in listModel[m].GetType().GetProperties()) { //dataRow.CreateCell(x).SetCellValue(string.Format("{0}", column.GetValue(listModel[m], null))); if (func == null) { //dataRow.CreateCell(x).SetCellValue(string.Format("{0}", column.GetValue(listModel[m], null))); ICell icell = dataRow.CreateCell(x); ICellValeSet(column.PropertyType.FullName, string.Format("{0}", column.GetValue(listModel[m], null)), icell); } else dataRow.CreateCell(x).SetCellValue(func(column.Name, column.GetValue(listModel[m], null)));//委托处理 x++; } rowIndex++; } } workbook.Write(ms); ms.Flush(); ms.Position = 0; workbook = null; return ms; } #endregion List反射导出Excel #region List反射导出Excel(根据已经选择的字段) public delegate string DataFormart(string key, object value); private static string entrySpace = "WX.CRM.Model.Entity";//嵌套实体的命名空间 /// /// List反射导出Excel(根据以选择的字段) /// /// /// 实体列表 /// 工作表名称 /// 一个工作簿的数据量(不能超过65536) /// 已经选择的字段 /// 返回一个流 public static Stream ExportListModelToExcel(List listModel, string sheetName, int sheetSize, string checkedFilds, DataFormart func) { checkedFilds = checkedFilds.ToUpper(); HSSFWorkbook workbook = new HSSFWorkbook(); MemoryStream ms = new MemoryStream(); string columnName = string.Empty; int x = 0; DisplayNameAttribute attribute = null; if (sheetSize > 65536) sheetSize = 65536; int sheetCout = (listModel.Count / sheetSize) + 1;//获取一个工作簿中多少页 for (int i = 0; i < sheetCout; i++) { ISheet sheet = workbook.CreateSheet(sheetName + (i + 1)); IRow headerRow = sheet.CreateRow(0); // 设置表头. x = 0; foreach (PropertyInfo info in typeof(T).GetProperties()) { if (info.PropertyType.FullName.IndexOf(entrySpace) > -1)//判断该字段是否为model里面的模型对象 { foreach (PropertyInfo childInfo in info.PropertyType.GetProperties()) { if (checkedFilds.IndexOf("[" + childInfo.Name.ToUpper() + "]") == -1)//如果没有选中该字段跳出这个继续 continue; attribute = (DisplayNameAttribute)Attribute.GetCustomAttribute(childInfo, typeof(DisplayNameAttribute)); headerRow.CreateCell(x).SetCellValue(attribute == null ? childInfo.Name : attribute.DisplayName);//获取类中的DisplayName属性 x++; } } else { if (checkedFilds.IndexOf("[" + info.Name.ToUpper() + "]") == -1)//如果没有选中该字段跳出这个继续 continue; attribute = (DisplayNameAttribute)Attribute.GetCustomAttribute(info, typeof(DisplayNameAttribute)); headerRow.CreateCell(x).SetCellValue(attribute == null ? info.Name : attribute.DisplayName);//获取类中的DisplayName属性 x++; } } // 绑定值 int rowIndex = 1; int mcount = (i + 1) * sheetSize > listModel.Count ? listModel.Count : (i + 1) * sheetSize; for (int m = (i * sheetSize); m < mcount; m++) { x = 0; IRow dataRow = sheet.CreateRow(rowIndex); foreach (PropertyInfo column in listModel[m].GetType().GetProperties()) { if (column.PropertyType.FullName.IndexOf(entrySpace) > -1)//判断该字段是否为model里面的模型对象 { foreach (PropertyInfo childColumn in column.PropertyType.GetProperties()) { if (checkedFilds.IndexOf("[" + childColumn.Name.ToUpper() + "]") == -1)//如果没有选中该字段跳出这个继续 continue; if (func == null) { ICell icell = dataRow.CreateCell(x); ICellValeSet(childColumn.PropertyType.FullName, string.Format("{0}", childColumn.GetValue(column.GetValue(listModel[m], null), null)), icell); } else dataRow.CreateCell(x).SetCellValue(func(childColumn.Name, childColumn.GetValue(column.GetValue(listModel[m], null), null)));//委托处理 x++; } } else { if (checkedFilds.IndexOf("[" + column.Name.ToUpper() + "]") == -1)//如果没有选中该字段跳出这个继续 continue; if (func == null) { ICell icell = dataRow.CreateCell(x); ICellValeSet(column.PropertyType.FullName, string.Format("{0}", column.GetValue(listModel[m], null)), icell); } else dataRow.CreateCell(x).SetCellValue(func(column.Name, column.GetValue(listModel[m], null)));//委托处理 x++; } } rowIndex++; } } workbook.Write(ms); ms.Flush(); ms.Position = 0; workbook = null; return ms; } /// /// List反射导出Excel(根据以选择的字段,顺序按照checkedFilds顺序,类型按照数据类型) /// /// /// 实体列表 /// 工作表名称 /// 一个工作簿的数据量(不能超过65536) /// 已经选择的字段 /// 已经选择的字段 中文名称 /// 返回一个流 public static Stream ExportListModelToExcel(List listModel, string sheetName, int sheetSize, string checkedFilds, string checkedTtile, DataFormart func) { checkedFilds = checkedFilds.ToUpper(); HSSFWorkbook workbook = new HSSFWorkbook(); MemoryStream ms = new MemoryStream(); string columnName = string.Empty; int x = 0; if (sheetSize > 65536) sheetSize = 65536; int sheetCout = (listModel.Count / sheetSize) + 1;//获取一个工作簿中多少页 Dictionary fildAndTitle = new Dictionary();//存储字段和中文标题 string[] dataTitle = checkedTtile.Split(','); checkedFilds = checkedFilds.Replace("[", ""); checkedFilds = checkedFilds.Length > 0 ? checkedFilds.Substring(0, checkedFilds.Length - 1) : checkedFilds; string[] dataFilds = checkedFilds.Split(']'); try { for (int i = 0; i < dataFilds.Length; i++) { string fild = dataFilds[i].Trim(); string title = dataTitle[i].Trim(); if (fild != "") { fildAndTitle.Add(fild, title); } } //--------------------------------先获取所有数据---------------------------------------- List> allData = new List>(); ExcelCell cell = null; string filedName = string.Empty; for (int i = 0; i < listModel.Count; i++) { Dictionary row = new Dictionary(); foreach (PropertyInfo column in listModel[i].GetType().GetProperties()) { if (column.PropertyType.FullName.IndexOf(entrySpace) > -1)//判断该字段是否为model里面的模型对象 { foreach (PropertyInfo childColumn in column.PropertyType.GetProperties()) { filedName = childColumn.Name.ToUpper(); if (!fildAndTitle.ContainsKey(filedName))//如果没有选中该字段跳出这个继续 continue; cell = new ExcelCell(); if (func == null) cell.nvalue = string.Format("{0}", childColumn.GetValue(column.GetValue(listModel[i], null), null)); else cell.nvalue = func(childColumn.Name, childColumn.GetValue(column.GetValue(listModel[i], null), null));//委托处理 cell.type = childColumn.PropertyType.FullName; cell.fild = filedName; cell.title = fildAndTitle[filedName]; if (row.ContainsKey(filedName)) continue; row.Add(childColumn.Name.ToUpper(), cell); } } else { filedName = column.Name.ToUpper(); if (!fildAndTitle.ContainsKey(filedName))//如果没有选中该字段跳出这个继续 continue; cell = new ExcelCell(); if (func == null) cell.nvalue = string.Format("{0}", column.GetValue(listModel[i], null)); else cell.nvalue = func(column.Name, column.GetValue(listModel[i], null));//委托处理 cell.type = column.PropertyType.FullName; cell.fild = filedName; cell.title = fildAndTitle[filedName]; if (row.ContainsKey(filedName)) continue; row.Add(filedName, cell); } } allData.Add(row); } //-----------------------------------end--------------------------------------- //-----------------------------------生成excel--------------------------------- //ICellStyle dateStyle = Getcellstyle(workbook, stylexls.时间); //ICellStyle numberStyle = Getcellstyle(workbook, stylexls.数字); for (int i = 0; i < sheetCout; i++) { ISheet sheet = workbook.CreateSheet(sheetName + (i + 1)); IRow headerRow = sheet.CreateRow(0); // 设置表头. x = 0; foreach (string title in dataTitle) { headerRow.CreateCell(x).SetCellValue(title); x++; } // 绑定值 int rowIndex = 1; int mcount = (i + 1) * sheetSize > listModel.Count ? listModel.Count : (i + 1) * sheetSize; for (int m = (i * sheetSize); m < mcount; m++) { x = 0; IRow dataRow = sheet.CreateRow(rowIndex); Dictionary row = allData[m]; foreach (string fild in dataFilds) { cell = row[fild]; ICell icell = dataRow.CreateCell(x); //icell.CellStyle = Getcellstyle(workbook, GetCellType(cell.type)); //if (cell.type.IndexOf("System.Demail") > -1 || cell.type.IndexOf("System.Int") > -1) //{ // Double doub; // if (Double.TryParse(cell.nvalue, out doub)) // { // icell.CellStyle = numberStyle; // } // icell.SetCellValue(cell.nvalue); //} //else if (cell.type.IndexOf("System.DateTime") > -1) //{ // DateTime dt; // if (DateTime.TryParse(cell.nvalue, out dt)) // { // icell.CellStyle = dateStyle; // } // icell.SetCellValue(cell.nvalue); //} //else ICellValeSet(cell, icell); //icell.SetCellValue(cell.nvalue); x++; } rowIndex++; } } } catch (Exception ex) { LogHelper.Error("excel导出失败:" + ex.ToString()); } workbook.Write(ms); ms.Flush(); ms.Position = 0; workbook = null; return ms; } private static void ICellValeSet(string dbType, string dbValue, ICell icell) { switch (GetCellType(dbType)) { case stylexls.数字: int wovalue = 0; if (int.TryParse(dbValue, out wovalue)) { icell.SetCellValue(wovalue); } else { icell.SetCellValue(dbValue); } break; case stylexls.小数: double dobValue = 0; if (double.TryParse(dbValue, out dobValue)) { icell.SetCellValue(dobValue); } else { icell.SetCellValue(dbValue); } break; case stylexls.时间: DateTime timeValue; if (DateTime.TryParse(dbValue, out timeValue)) { icell.SetCellValue(timeValue.ToString("yyyy/MM/dd HH:mm:ss")); } else { icell.SetCellValue(""); } break; case stylexls.默认: icell.SetCellValue(dbValue.ToString()); break; } } private static void ICellValeSet(ExcelCell cell, ICell icell) { switch (GetCellType(cell.type)) { case stylexls.数字: int wovalue = 0; if (int.TryParse(cell.nvalue, out wovalue)) { icell.SetCellValue(wovalue); } else { icell.SetCellValue(cell.nvalue); } break; case stylexls.小数: double dobValue = 0; if (double.TryParse(cell.nvalue, out dobValue)) { icell.SetCellValue(dobValue); } else { icell.SetCellValue(cell.nvalue); } break; case stylexls.时间: DateTime timeValue; if (DateTime.TryParse(cell.nvalue, out timeValue)) { icell.SetCellValue(timeValue.ToString("yyyy/MM/dd HH:mm:ss")); } else { icell.SetCellValue(""); } break; case stylexls.默认: icell.SetCellValue(cell.nvalue.ToString()); break; } } private static stylexls GetCellType(string fullTypeName) { if (fullTypeName == null) return stylexls.默认; if (fullTypeName.IndexOf("System.Decimal") > -1) return stylexls.小数; if (fullTypeName.IndexOf("System.Int") > -1) return stylexls.数字; if (fullTypeName.IndexOf("System.DateTime") > -1) return stylexls.时间; return stylexls.默认; } /// /// List反射导出Excel(根据以选择的字段,顺序按照checkedFilds顺序,类型按照数据类型) /// /// /// 实体列表 /// 工作表名称 /// 一个工作簿的数据量(不能超过65536) /// 已经选择的字段 /// 已经选择的字段 中文名称 /// 返回一个流 public static Stream ExportListModelToExcelMerge(List listModel, string sheetName, int sheetSize, string checkedFilds, string checkedTtile, DataFormart func, MergeExcelModel mergeExcelModel) { checkedFilds = checkedFilds.ToUpper(); HSSFWorkbook workbook = new HSSFWorkbook(); MemoryStream ms = new MemoryStream(); string columnName = string.Empty; int x = 0; if (sheetSize > 65536) sheetSize = 65536; int sheetCout = (listModel.Count / sheetSize) + 1;//获取一个工作簿中多少页 Dictionary fildAndTitle = new Dictionary();//存储字段和中文标题 string[] dataTitle = checkedTtile.Split(','); checkedFilds = checkedFilds.Replace("[", ""); checkedFilds = checkedFilds.Length > 0 ? checkedFilds.Substring(0, checkedFilds.Length - 1) : checkedFilds; string[] dataFilds = checkedFilds.Split(']'); try { for (int i = 0; i < dataFilds.Length; i++) { string fild = dataFilds[i].Trim(); string title = dataTitle[i].Trim(); if (fild != "") { fildAndTitle.Add(fild, title); } } //--------------------------------先获取所有数据---------------------------------------- List> allData = new List>(); ExcelCell cell = null; string filedName = string.Empty; for (int i = 0; i < listModel.Count; i++) { Dictionary row = new Dictionary(); foreach (PropertyInfo column in listModel[i].GetType().GetProperties()) { if (column.PropertyType.FullName.IndexOf(entrySpace) > -1)//判断该字段是否为model里面的模型对象 { foreach (PropertyInfo childColumn in column.PropertyType.GetProperties()) { filedName = childColumn.Name.ToUpper(); if (!fildAndTitle.ContainsKey(filedName))//如果没有选中该字段跳出这个继续 continue; cell = new ExcelCell(); if (func == null) cell.nvalue = string.Format("{0}", childColumn.GetValue(column.GetValue(listModel[i], null), null)); else cell.nvalue = func(childColumn.Name, childColumn.GetValue(column.GetValue(listModel[i], null), null));//委托处理 cell.type = childColumn.PropertyType.FullName; cell.fild = filedName; cell.title = fildAndTitle[filedName]; if (row.ContainsKey(filedName)) continue; row.Add(childColumn.Name.ToUpper(), cell); } } else { filedName = column.Name.ToUpper(); if (!fildAndTitle.ContainsKey(filedName))//如果没有选中该字段跳出这个继续 continue; cell = new ExcelCell(); if (func == null) cell.nvalue = string.Format("{0}", column.GetValue(listModel[i], null)); else cell.nvalue = func(column.Name, column.GetValue(listModel[i], null));//委托处理 cell.type = column.PropertyType.FullName; cell.fild = filedName; cell.title = fildAndTitle[filedName]; if (row.ContainsKey(filedName)) continue; row.Add(filedName, cell); } } allData.Add(row); } //-----------------------------------end--------------------------------------- //-----------------------------------生成excel--------------------------------- for (int i = 0; i < sheetCout; i++) { ISheet sheet = workbook.CreateSheet(sheetName + (i + 1)); IRow headerRow = sheet.CreateRow(0); // 设置表头. x = 0; foreach (string title in dataTitle) { headerRow.CreateCell(x).SetCellValue(title); x++; } // 绑定值 int rowIndex = 1; int mcount = (i + 1) * sheetSize > listModel.Count ? listModel.Count : (i + 1) * sheetSize; string lastKey = ""; var hasmerge = false; var startMerrow = 0; for (int m = (i * sheetSize); m < mcount; m++) { x = 0; IRow dataRow = sheet.CreateRow(rowIndex); Dictionary row = allData[m]; var rowmerge = false; foreach (string fild in dataFilds) { cell = row[fild]; ICell icell = dataRow.CreateCell(x); ICellValeSet(cell, icell); if (mergeExcelModel.MergeRow.Contains(fild.ToLower()) && m > 0) { var prerow = allData[m - 1]; lastKey = prerow[mergeExcelModel.MergeId].nvalue; var nowrow = allData[m]; var nowkey = nowrow[mergeExcelModel.MergeId].nvalue; if (lastKey == nowkey && !hasmerge) { hasmerge = true; //先记录需要合并 startMerrow = rowIndex - 1; } //如果最后一行 则直接合并 if (hasmerge && rowIndex == listModel.Count) { CellRangeAddress region = new CellRangeAddress(startMerrow, rowIndex, x, x); sheet.AddMergedRegion(region); rowmerge = true; } //如果下一行 的匹配键值跟上一个不一致 则直接合并到上一行单元格 if (lastKey != nowkey && hasmerge) { CellRangeAddress region = new CellRangeAddress(startMerrow, rowIndex - 1, x, x); sheet.AddMergedRegion(region); rowmerge = true; } } x++; } if (rowmerge) { hasmerge = false; } rowIndex++; } } } catch (Exception ex) { LogHelper.Error("excel导出失败:" + ex.ToString()); } workbook.Write(ms); ms.Flush(); ms.Position = 0; workbook = null; return ms; } #endregion List反射导出Excel(根据已经选择的字段) #region 由DataSet导出Excel /// /// 由DataSet导出Excel /// /// 要导出数据的DataTable /// 工作表名称 /// Excel工作表 public static Stream ExportDataSetToExcel(DataSet sourceDs, string sheetName) { HSSFWorkbook workbook = new HSSFWorkbook(); MemoryStream ms = new MemoryStream(); string[] sheetNames = sheetName.Split(','); for (int i = 0; i < sheetNames.Length; i++) { ISheet sheet = workbook.CreateSheet(sheetNames[i]); IRow headerRow = sheet.CreateRow(0); // handling header. foreach (DataColumn column in sourceDs.Tables[i].Columns) headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName); // handling value. int rowIndex = 1; foreach (DataRow row in sourceDs.Tables[i].Rows) { IRow dataRow = sheet.CreateRow(rowIndex); foreach (DataColumn column in sourceDs.Tables[i].Columns) { ICell icell = dataRow.CreateCell(column.Ordinal); ICellValeSet(column.DataType.FullName, row[column].ToString(), icell); //dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString()); } rowIndex++; } } workbook.Write(ms); ms.Flush(); ms.Position = 0; workbook = null; return ms; } /// /// 由DataSet导出Excel /// /// 要导出数据的DataTable /// 指定Excel工作表名称 /// Excel工作表 public static void ExportDataSetToExcel(DataSet sourceDs, string fileName, string sheetName) { MemoryStream ms = ExportDataSetToExcel(sourceDs, sheetName) as MemoryStream; HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName); HttpContext.Current.Response.BinaryWrite(ms.ToArray()); HttpContext.Current.Response.End(); ms.Close(); ms = null; } /// /// 由DataTable导出Excel /// /// 要导出数据的DataTable /// Excel工作表 public static Stream ExportDataTableToExcel(DataTable sourceTable, string sheetName) { HSSFWorkbook workbook = new HSSFWorkbook(); MemoryStream ms = new MemoryStream(); ISheet sheet = workbook.CreateSheet(sheetName); IRow headerRow = sheet.CreateRow(0); // handling header. foreach (DataColumn column in sourceTable.Columns) headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName); // handling value. int rowIndex = 1; foreach (DataRow row in sourceTable.Rows) { IRow dataRow = sheet.CreateRow(rowIndex); foreach (DataColumn column in sourceTable.Columns) { ICell icell = dataRow.CreateCell(column.Ordinal); ICellValeSet(column.DataType.FullName, row[column].ToString(), icell); } rowIndex++; } workbook.Write(ms); ms.Flush(); ms.Position = 0; sheet = null; headerRow = null; workbook = null; return ms; } /// /// 头部委托函数(可以自己定义重写excle的头部) /// /// /// public delegate string HeadFormart(string key); /// /// datable导出excle /// /// DataTable数据源 /// 工作簿名称 /// 被选中的字段 /// excle头部格式化委托 /// 数据格式委托 /// public static Stream ExportDataTableToExcel(DataTable sourceTable, string sheetName, string checkedFilds, string checkedTtile, DataFormart func) { HSSFWorkbook workbook = new HSSFWorkbook(); MemoryStream ms = new MemoryStream(); ISheet sheet = workbook.CreateSheet(sheetName); IRow headerRow = sheet.CreateRow(0); checkedFilds = checkedFilds.ToLower(); // handling header. checkedFilds = checkedFilds.ToUpper(); Dictionary fildAndTitle = new Dictionary();//存储字段和中文标题 string[] dataTitle = checkedTtile.Split(','); checkedFilds = checkedFilds.Replace("[", ""); checkedFilds = checkedFilds.Length > 0 ? checkedFilds.Substring(0, checkedFilds.Length - 1) : checkedFilds; string[] dataFilds = checkedFilds.Split(']'); int cellIndex = 0; try { for (int i = 0; i < dataFilds.Length; i++) { string fild = dataFilds[i].Trim(); string title = dataTitle[i].Trim(); if (fild != "" && !fildAndTitle.ContainsKey(fild)) { fildAndTitle.Add(fild, title); } } //--------------------------------先获取所有数据---------------------------------------- List> allData = new List>(); ExcelCell cell = null; string filedName = string.Empty; for (int i = 0; i < sourceTable.Rows.Count; i++) { Dictionary row = new Dictionary(); foreach (DataColumn column in sourceTable.Columns) { filedName = column.ColumnName.ToUpper(); if (!fildAndTitle.ContainsKey(filedName))//如果没有选中该字段跳出这个继续 continue; cell = new ExcelCell(); if (func == null) cell.nvalue = string.Format("{0}", sourceTable.Rows[i][column].ToString()); else cell.nvalue = func(column.ColumnName, sourceTable.Rows[i][column]);//委托处理 cell.fild = filedName; cell.type = column.DataType.FullName; cell.title = fildAndTitle[filedName]; row.Add(filedName, cell); } allData.Add(row); } //-----------------------------------end--------------------------------------- //---------------------------------设置头部------------------------------------ foreach (string title in dataTitle)//根据传过来的 标题生成excel标题 { headerRow.CreateCell(cellIndex).SetCellValue(title); cellIndex++; } //----------------------------------end---------------------------------------- //-------------------------------循环设置数据---------------------------------- int rowIndex = 1; foreach (Dictionary row in allData) { cellIndex = 0; IRow dataRow = sheet.CreateRow(rowIndex); foreach (string fild in dataFilds) { if (!row.ContainsKey(fild)) continue; cell = row[fild]; ICell icell = dataRow.CreateCell(cellIndex); ICellValeSet(cell, icell); //icell.SetCellValue(cell.nvalue); cellIndex++; } rowIndex++; } } catch (Exception ex) { LogHelper.Error("excel导出失败:" + ex.ToString()); } //---------------------------------end---------------------------------------- workbook.Write(ms); ms.Flush(); ms.Position = 0; sheet = null; headerRow = null; workbook = null; return ms; } /// /// datable导出excle /// /// DataTable数据源 /// 工作簿名称 /// 被选中的字段 /// excle头部格式化委托 /// 数据格式委托 /// public static Stream ExportDataTableToExcel(DataTable sourceTable, string sheetName, string checkedFilds, HeadFormart head, DataFormart func) { HSSFWorkbook workbook = new HSSFWorkbook(); MemoryStream ms = new MemoryStream(); ISheet sheet = workbook.CreateSheet(sheetName); IRow headerRow = sheet.CreateRow(0); checkedFilds = checkedFilds.ToLower(); // handling header. int cellIndex = 0; foreach (DataColumn column in sourceTable.Columns) { if (checkedFilds.IndexOf("[" + column.ColumnName.ToLower() + "]") > -1)//字段是否被选择 { if (head != null) headerRow.CreateCell(cellIndex).SetCellValue(head(column.ColumnName)); else headerRow.CreateCell(cellIndex).SetCellValue(column.ColumnName); cellIndex++; } } // handling value. int rowIndex = 1; foreach (DataRow row in sourceTable.Rows) { IRow dataRow = sheet.CreateRow(rowIndex); cellIndex = 0; foreach (DataColumn column in sourceTable.Columns) { if (checkedFilds.IndexOf("[" + column.ColumnName.ToLower() + "]") > -1)//字段是否被选择 { if (func != null) { dataRow.CreateCell(cellIndex).SetCellValue(func(column.ColumnName, row[column].ToString())); } else { ICell icell = dataRow.CreateCell(cellIndex); ICellValeSet(column.DataType.FullName, row[column].ToString(), icell); //dataRow.CreateCell(cellIndex).SetCellValue(row[column].ToString()); } cellIndex++; } } rowIndex++; } workbook.Write(ms); ms.Flush(); ms.Position = 0; sheet = null; headerRow = null; workbook = null; return ms; } /// /// 由DataTable导出Excel /// /// 要导出数据的DataTable /// 指定Excel工作表名称 /// Excel工作表 public static void ExportDataTableToExcel(DataTable sourceTable, string fileName, string sheetName) { MemoryStream ms = ExportDataTableToExcel(sourceTable, sheetName) as MemoryStream; HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName); HttpContext.Current.Response.ContentType = "application/vnd.ms-excel"; HttpContext.Current.Response.Charset = "utf-8"; HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8; HttpContext.Current.Response.BinaryWrite(ms.ToArray()); HttpContext.Current.Response.End(); ms.Close(); ms = null; } #endregion 由DataSet导出Excel #region 由Render导出Excel /// ///由Render导出Excel /// /// /// public static MemoryStream RenderToExcel(IDataReader reader) { MemoryStream ms = new MemoryStream(); using (reader) { IWorkbook workbook = new HSSFWorkbook(); ISheet sheet = workbook.CreateSheet(); IRow headerRow = sheet.CreateRow(0); int cellCount = reader.FieldCount; // handling header. for (int i = 0; i < cellCount; i++) { headerRow.CreateCell(i).SetCellValue(reader.GetName(i)); } // handling value. int rowIndex = 1; while (reader.Read()) { IRow dataRow = sheet.CreateRow(rowIndex); for (int i = 0; i < cellCount; i++) { dataRow.CreateCell(i).SetCellValue(reader[i].ToString()); } rowIndex++; } workbook.Write(ms); ms.Flush(); ms.Position = 0; } return ms; } #endregion 由Render导出Excel #region 由Excel导入DataTable /// /// 由Excel导入DataTable /// /// Excel文件流 /// Excel工作表名称 /// Excel表头行索引 /// DataTable public static DataTable ImportDataTableFromExcel(Stream excelFileStream, string sheetName, int headerRowIndex) { HSSFWorkbook workbook = new HSSFWorkbook(excelFileStream); ISheet sheet = workbook.GetSheet(sheetName); DataTable table = new DataTable(); IRow headerRow = sheet.GetRow(headerRowIndex); int cellCount = headerRow.LastCellNum; for (int i = headerRow.FirstCellNum; i < cellCount; i++) { DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue); table.Columns.Add(column); } for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++) { IRow row = sheet.GetRow(i); DataRow dataRow = table.NewRow(); for (int j = row.FirstCellNum; j < cellCount; j++) dataRow[j] = string.Format("{0}", row.GetCell(j)); table.Rows.Add(dataRow); } excelFileStream.Close(); workbook = null; sheet = null; return table; } /// /// 由Excel导入DataTable /// /// Excel文件路径,为物理路径。 /// Excel工作表名称 /// Excel表头行索引 /// DataTable public static DataTable ImportDataTableFromExcel(string excelFilePath, string sheetName, int headerRowIndex) { using (FileStream stream = System.IO.File.OpenRead(excelFilePath)) { return ImportDataTableFromExcel(stream, sheetName, headerRowIndex); } } /// /// 由Excel导入DataTable /// /// Excel文件流 /// Excel工作表索引 /// Excel表头行索引 /// DataTable public static DataTable ImportDataTableFromExcel(Stream excelFileStream, int sheetIndex, int headerRowIndex) { HSSFWorkbook workbook = new HSSFWorkbook(excelFileStream); ISheet sheet = workbook.GetSheetAt(sheetIndex); DataTable table = new DataTable(); IRow headerRow = sheet.GetRow(headerRowIndex); int cellCount = headerRow.LastCellNum; for (int i = headerRow.FirstCellNum; i < cellCount; i++) { if (headerRow.GetCell(i) == null || headerRow.GetCell(i).StringCellValue.Trim() == "") { // 如果遇到第一个空列,则不再继续向后读取 cellCount = i + 1; break; } DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue); table.Columns.Add(column); } for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++) { IRow row = sheet.GetRow(i); if (row == null || row.GetCell(0) == null || row.GetCell(0).ToString().Trim() == "") { // 如果遇到第一个空行,则不再继续向后读取 break; } DataRow dataRow = table.NewRow(); for (int j = row.FirstCellNum; j < cellCount; j++) { dataRow[j] = row.GetCell(j); } table.Rows.Add(dataRow); } excelFileStream.Close(); workbook = null; sheet = null; return table; } /// /// 由Excel导入DataTable /// /// Excel文件路径,为物理路径。 /// Excel工作表索引 /// Excel表头行索引 /// DataTable public static DataTable ImportDataTableFromExcel(string excelFilePath, int sheetIndex, int headerRowIndex) { using (FileStream stream = System.IO.File.OpenRead(excelFilePath)) { return ImportDataTableFromExcel(stream, sheetIndex, headerRowIndex); } } #endregion 由Excel导入DataTable #region 由Excel导入DataSet,如果有多个工作表,则导入多个DataTable /// /// 由Excel导入DataSet,如果有多个工作表,则导入多个DataTable /// /// Excel文件流 /// Excel表头行索引 /// DataSet public static DataSet ImportDataSetFromExcel(Stream excelFileStream, int headerRowIndex) { DataSet ds = new DataSet(); HSSFWorkbook workbook = new HSSFWorkbook(excelFileStream); for (int a = 0, b = workbook.NumberOfSheets; a < b; a++) { ISheet sheet = workbook.GetSheetAt(a); DataTable table = new DataTable(); IRow headerRow = sheet.GetRow(headerRowIndex); int cellCount = headerRow.LastCellNum; for (int i = headerRow.FirstCellNum; i < cellCount; i++) { if (headerRow.GetCell(i) == null || headerRow.GetCell(i).StringCellValue.Trim() == "") { // 如果遇到第一个空列,则不再继续向后读取 cellCount = i + 1; break; } DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue); table.Columns.Add(column); } for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++) { IRow row = sheet.GetRow(i); if (row == null || row.GetCell(0) == null || row.GetCell(0).ToString().Trim() == "") { // 如果遇到第一个空行,则不再继续向后读取 break; } DataRow dataRow = table.NewRow(); for (int j = row.FirstCellNum; j < cellCount; j++) { if (row.GetCell(j) != null) { dataRow[j] = row.GetCell(j).ToString(); } } table.Rows.Add(dataRow); } ds.Tables.Add(table); } excelFileStream.Close(); workbook = null; return ds; } /// /// 由Excel导入DataSet,如果有多个工作表,则导入多个DataTable /// /// Excel文件路径,为物理路径。 /// Excel表头行索引 /// DataSet public static DataSet ImportDataSetFromExcel(string excelFilePath, int headerRowIndex) { using (FileStream stream = System.IO.File.OpenRead(excelFilePath)) { return ImportDataSetFromExcel(stream, headerRowIndex); } } #endregion 由Excel导入DataSet,如果有多个工作表,则导入多个DataTable #region 获取字体样式 /// /// 获取字体样式 /// /// Excel操作类 /// 字体名 /// 字体颜色 /// 字体大小 /// public static IFont GetFontStyle(HSSFWorkbook hssfworkbook, string fontfamily, HSSFColor fontcolor, int fontsize) { IFont font1 = hssfworkbook.CreateFont(); if (string.IsNullOrEmpty(fontfamily)) { font1.FontName = fontfamily; } if (fontcolor != null) { font1.Color = fontcolor.Indexed; } font1.IsItalic = true; font1.FontHeightInPoints = (short)fontsize; return font1; } #endregion 获取字体样式 #region 获取单元格样式 // /// 获取单元格样式 /// /// Excel操作类 /// 单元格字体 /// 图案的颜色 /// 图案样式 /// 单元格背景 /// 垂直对齐方式 /// 垂直对齐方式 /// public static ICellStyle GetCellStyle(HSSFWorkbook hssfworkbook, IFont font, HSSFColor fillForegroundColor, FillPattern fillPattern, HSSFColor fillBackgroundColor, HorizontalAlignment ha, VerticalAlignment va) { ICellStyle cellstyle = hssfworkbook.CreateCellStyle(); cellstyle.FillPattern = fillPattern; cellstyle.Alignment = ha; cellstyle.VerticalAlignment = va; if (fillForegroundColor != null) { cellstyle.FillForegroundColor = fillForegroundColor.Indexed; } if (fillBackgroundColor != null) { cellstyle.FillBackgroundColor = fillBackgroundColor.Indexed; } if (font != null) { cellstyle.SetFont(font); } //有边框 cellstyle.BorderBottom = BorderStyle.Thin; cellstyle.BorderLeft = BorderStyle.Thin; cellstyle.BorderRight = BorderStyle.Thin; cellstyle.BorderTop = BorderStyle.Thin; return cellstyle; } #endregion 获取单元格样式 #region 合并单元格 /// /// 合并单元格 /// /// 要合并单元格所在的sheet /// 开始行的索引 /// 结束行的索引 /// 开始列的索引 /// 结束列的索引 public static void SetCellRangeAddress(ISheet sheet, int rowstart, int rowend, int colstart, int colend) { CellRangeAddress cellRangeAddress = new CellRangeAddress(rowstart, rowend, colstart, colend); sheet.AddMergedRegion(cellRangeAddress); } #endregion 合并单元格 #region 定义单元格常用到样式的枚举 public enum stylexls { 头, url, 时间, 数字, 小数, 钱, 百分比, 中文大写, 科学计数法, 默认 } #endregion 定义单元格常用到样式的枚举 #region 定义单元格常用到样式 例子 public static ICellStyle Getcellstyle(IWorkbook wb, stylexls str) { ICellStyle cellStyle = wb.CreateCellStyle(); //定义几种字体 //也可以一种字体,写一些公共属性,然后在下面需要时加特殊的 IFont font12 = wb.CreateFont(); font12.FontHeightInPoints = 10; font12.FontName = "微软雅黑"; IFont font = wb.CreateFont(); font.FontName = "微软雅黑"; IFont fontcolorblue = wb.CreateFont(); fontcolorblue.Color = HSSFColor.OliveGreen.Blue.Index; // fontcolorblue.IsItalic = true;//下划线 fontcolorblue.FontName = "微软雅黑"; /* //边框 cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Dotted; cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Hair; cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Hair; cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Dotted; //边框颜色 cellStyle.BottomBorderColor = HSSFColor.OliveGreen.Blue.Index; cellStyle.TopBorderColor = HSSFColor.OliveGreen.Blue.Index; //背景图形 cellStyle.FillForegroundColor = HSSFColor.White.Index; // cellStyle.FillPattern = FillPatternType.NO_FILL; cellStyle.FillBackgroundColor = HSSFColor.Blue.Index; //水平对齐 cellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Left; //垂直对齐 cellStyle.VerticalAlignment = VerticalAlignment.Center; //自动换行 cellStyle.WrapText = true; //缩进;当设置为1时,前面留的空白太大了。希旺官网改进。或者是我设置的不对 cellStyle.Indention = 0; */ //上面基本都是设共公的设置 //下面列出了常用的字段类型 switch (str) { case stylexls.头: // cellStyle.FillPattern = FillPatternType.LEAST_DOTS; cellStyle.SetFont(font12); break; case stylexls.时间: IDataFormat datastyle = wb.CreateDataFormat(); cellStyle.DataFormat = datastyle.GetFormat("yyyy/mm/dd"); cellStyle.SetFont(font); break; case stylexls.数字: cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("0.00"); cellStyle.SetFont(font); break; case stylexls.钱: IDataFormat format = wb.CreateDataFormat(); cellStyle.DataFormat = format.GetFormat("¥#,##0"); cellStyle.SetFont(font); break; case stylexls.url: fontcolorblue.Underline = FontUnderlineType.Single; cellStyle.SetFont(fontcolorblue); break; case stylexls.百分比: cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("0.00%"); cellStyle.SetFont(font); break; case stylexls.中文大写: IDataFormat format1 = wb.CreateDataFormat(); cellStyle.DataFormat = format1.GetFormat("[DbNum2][$-804]0"); cellStyle.SetFont(font); break; case stylexls.科学计数法: cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("0.00E+00"); cellStyle.SetFont(font); break; case stylexls.默认: cellStyle.SetFont(font); break; } return cellStyle; } #endregion 定义单元格常用到样式 例子 #region 其他操作 /// /// 将Excel的列索引转换为列名,列索引从0开始,列名从A开始。如第0列为A,第1列为B... /// /// 列索引 /// 列名,如第0列为A,第1列为B... public static string ConvertColumnIndexToColumnName(int index) { index = index + 1; int system = 26; char[] digArray = new char[100]; int i = 0; while (index > 0) { int mod = index % system; if (mod == 0) mod = system; digArray[i++] = (char)(mod - 1 + 'A'); index = (index - 1) / 26; } StringBuilder sb = new StringBuilder(i); for (int j = i - 1; j >= 0; j--) { sb.Append(digArray[j]); } return sb.ToString(); } /// /// 转化日期 /// /// 日期 /// public static DateTime ConvertDate(string date) { DateTime dt = new DateTime(); string[] time = date.Split('-'); int year = Convert.ToInt32(time[2]); int month = Convert.ToInt32(time[0]); int day = Convert.ToInt32(time[1]); string years = Convert.ToString(year); string months = Convert.ToString(month); string days = Convert.ToString(day); if (months.Length == 4) { dt = Convert.ToDateTime(date); } else { string rq = ""; if (years.Length == 1) { years = "0" + years; } if (months.Length == 1) { months = "0" + months; } if (days.Length == 1) { days = "0" + days; } rq = "20" + years + "-" + months + "-" + days; dt = Convert.ToDateTime(rq); } return dt; } /// /// 给行创建简单的单元格(必须为以选中的字段) /// /// 表格行 /// 列的位置 /// 值 /// 当前字段 /// 选中的字段列表 public static void CreateSimpleCell(IRow row, ref int index, string value, string fild, string checkedFilds) { if (checkedFilds.IndexOf("[" + fild.ToUpper() + "]") > -1) { row.CreateCell(index).SetCellValue(value); index++; } } #endregion 其他操作 } public class ExcelCell { /// /// 英文字段名称 /// public string fild { get; set; } /// /// 字段的数据类型 /// public string type { get; set; } /// /// 字段的中文标题 /// public string title { get; set; } /// /// 字段的值 /// public string nvalue { get; set; } } public class MergeExcelModel { /// /// 匹配的数据 相同值的话进行合并 /// public string MergeId { get; set; } /// /// 要合并的列 /// public List MergeRow { get; set; } } }