public static byte[] ExportExcel<T>(Dictionary<string, string> columnsHeader, List<T> dataSource, string title = null, string footer = null)
{
IWorkbook workbook = new HSSFWorkbook();
ISheet sheet = workbook.CreateSheet("Sheet1");
sheet.DefaultColumnWidth = ; IRow row;
ICell cell; #region excel标题头
int rowIndex = ;
if (!string.IsNullOrEmpty(title))
{
ICellStyle cellStyle = workbook.CreateCellStyle();
cellStyle.VerticalAlignment = VerticalAlignment.Center;
cellStyle.Alignment = HorizontalAlignment.Center;
IFont font = workbook.CreateFont();
font.FontHeightInPoints = ;
font.Boldweight = ;
cellStyle.SetFont(font);
var region = new CellRangeAddress(, , , columnsHeader.Keys.Count > ? columnsHeader.Keys.Count - : );
sheet.AddMergedRegion(region);
//合并单元格后样式
((HSSFSheet)sheet).SetEnclosedBorderOfRegion(region, BorderStyle.Thin, NPOI.HSSF.Util.HSSFColor.Black.Index); row = sheet.CreateRow(rowIndex);
row.HeightInPoints = ;
cell = row.CreateCell();
cell.SetCellValue(title);
cell.CellStyle = cellStyle;
rowIndex++;
}
#endregion #region 列头
row = sheet.CreateRow(rowIndex);
row.HeightInPoints = ;
int cellIndex = ;
foreach (var value in columnsHeader.Values)
{
ICellStyle cellStyle = workbook.CreateCellStyle();
cellStyle = workbook.CreateCellStyle();
cellStyle.BorderBottom = BorderStyle.Thin;
cellStyle.BorderLeft = BorderStyle.Thin;
cellStyle.BorderRight = BorderStyle.Thin;
cellStyle.BorderTop = BorderStyle.Thin;
//背景色
cellStyle.FillForegroundColor = HSSFColor.Grey25Percent.Index;
cellStyle.FillPattern = FillPattern.SolidForeground;
//水平垂直居中
cellStyle.VerticalAlignment = VerticalAlignment.Center;
cellStyle.Alignment = HorizontalAlignment.Center;
IFont font = workbook.CreateFont();
font.FontHeightInPoints = ;
font.Boldweight = ;
cellStyle.SetFont(font); cell = row.CreateCell(cellIndex);
cell.CellStyle = cellStyle;
cell.SetCellValue(value);
cellIndex++;
}
rowIndex++;
#endregion #region 主题内容 //单元格样式 注:不要放循环里面,NPOI中调用workbook.CreateCellStyle()方法超过4000次会报错
ICellStyle contentStyle = workbook.CreateCellStyle();
contentStyle.BorderBottom = BorderStyle.Thin;
contentStyle.BorderLeft = BorderStyle.Thin;
contentStyle.BorderRight = BorderStyle.Thin;
contentStyle.BorderTop = BorderStyle.Thin;
contentStyle.VerticalAlignment = VerticalAlignment.Center;
IFont contentFont = workbook.CreateFont();
contentFont.FontHeightInPoints = ;
contentStyle.SetFont(contentFont); //日期格式样式
ICellStyle dateStyle = workbook.CreateCellStyle();
dateStyle.BorderBottom = BorderStyle.Thin;
dateStyle.BorderLeft = BorderStyle.Thin;
dateStyle.BorderRight = BorderStyle.Thin;
dateStyle.BorderTop = BorderStyle.Thin;
dateStyle.VerticalAlignment = VerticalAlignment.Center;
dateStyle.SetFont(contentFont);
IDataFormat format = workbook.CreateDataFormat();
dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd");
foreach (T item in dataSource)
{
row = sheet.CreateRow(rowIndex);
row.HeightInPoints = ;
rowIndex++;
Type type = item.GetType();
PropertyInfo[] properties = type.GetProperties();
if (properties.Length > )
{
cellIndex = ;
foreach (var key in columnsHeader.Keys)
{
cell = row.CreateCell(cellIndex);
cell.CellStyle = contentStyle; if (properties.Select(x => x.Name.ToLower()).Contains(key.ToLower()))
{
var property = properties.Where(x => x.Name.ToLower() == key.ToLower()).FirstOrDefault();
string drValue = property.GetValue(item) == null ? "" : property.GetValue(item).ToString();
//当类型类似DateTime?时
var fullType = property.PropertyType.Name == "Nullable`1" ? property.PropertyType.GetGenericArguments()[].FullName : property.PropertyType.FullName;
switch (fullType)
{
case "System.String": //字符串类型
cell.SetCellValue(drValue);
break;
case "System.DateTime": //日期类型
if (string.IsNullOrEmpty(drValue) || drValue == "0001/1/1 0:00:00")
{
cell.SetCellValue("");
}
else
{
DateTime dateV;
DateTime.TryParse(drValue, out dateV);
cell.SetCellValue(dateV); cell.CellStyle = dateStyle; //格式化显示
}
break;
case "System.Boolean": //布尔型
bool boolV = false;
bool.TryParse(drValue, out boolV);
cell.SetCellValue(boolV);
break;
case "System.Int16": //整型
case "System.Int32":
case "System.Int64":
case "System.Byte":
int intV = ;
int.TryParse(drValue, out intV);
cell.SetCellValue(intV);
break;
case "System.Decimal": //浮点型
case "System.Double":
double doubV = ;
double.TryParse(drValue, out doubV);
cell.SetCellValue(doubV);
break;
case "System.DBNull": //空值处理
cell.SetCellValue("");
break;
default:
cell.SetCellValue("");
break;
}
}
cellIndex++;
}
} }
#endregion #region 结尾行
if (!string.IsNullOrEmpty(footer))
{
ICellStyle cellStyle = workbook.CreateCellStyle();
cellStyle.VerticalAlignment = VerticalAlignment.Center;
cellStyle.Alignment = HorizontalAlignment.Center;
IFont font = workbook.CreateFont();
font.FontHeightInPoints = ;
font.Boldweight = ;
cellStyle.SetFont(font);
var region = new CellRangeAddress(rowIndex, rowIndex, , columnsHeader.Keys.Count > ? columnsHeader.Keys.Count - : );
sheet.AddMergedRegion(region);
//合并单元格后样式
((HSSFSheet)sheet).SetEnclosedBorderOfRegion(region, BorderStyle.Thin, NPOI.HSSF.Util.HSSFColor.Black.Index); row = sheet.CreateRow(rowIndex);
row.HeightInPoints = ;
cell = row.CreateCell();
cell.SetCellValue(footer);
cell.CellStyle = cellStyle;
}
#endregion using (MemoryStream ms = new MemoryStream())
{
workbook.Write(ms);
ms.Flush();
ms.Seek(, SeekOrigin.Begin);
return ms.ToArray();
                //或者直接导出不用返回值  var response = System.Web.HttpContext.Current.Response;
//response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
//response.ContentType = "application/vnd.ms-excel";
//response.AddHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");
//response.BinaryWrite(ms.ToArray());
//response.Buffer = true;
//response.Flush();
//response.End();
            }
}

Controller中调用:

Dictionary<string, string> collection = new Dictionary<string, string>();
collection.Add("字段名", "显示名");
collection.Add("name", "姓名");
collection.Add("age", "年龄");
collection.Add("grade", "分数"); var byteInfo = JXUtil.ExcelHelper.ExportExcel<Student>(collection, list);
return File(byteInfo, "application/vnd.ms-excel", string.Format("记录-{0}.xls", DateTime.Now.ToString("yyyyMMddHHmm")));
//无返回值直接调用    ExcelHelper.ExportExcel(collection, list, "广告位excel");

  

NOPI 导出excel 通用方法的更多相关文章

  1. java根据xml配置文件导出excel通用方法

    java web项目中时常会用到导出功能,而导出excel几乎是每个项目必备的功能之一.针对形形色色的导出方法及个人平时的工作经验,特将导出excel方法整理成通用的方法,根据xml配置来实现特定的导 ...

  2. NPOI 导出excel 通用方法

    public static byte[] ExportExcel<T>(Dictionary<string, string> columnsHeader, List<T& ...

  3. java导出excel通用方法

    首先需要引入的jar包: 正式代码了. import java.io.FileOutputStream; import java.io.OutputStream; import java.net.UR ...

  4. NPOI导入导出EXCEL通用类,供参考,可直接使用在WinForm项目中

    以下是NPOI导入导出EXCEL通用类,是在别人的代码上进行优化的,兼容xls与xlsx文件格式,供参考,可直接使用在WinForm项目中,由于XSSFWorkbook类型的Write方法限制,Wri ...

  5. NOPI导出Excel

    NOPI导出Excel /// <summary> /// 导出的方法 Excel样式 /// </summary> /// <param name="ds&q ...

  6. MVC NPOI Linq导出Excel通用类

    之前写了一个模型导出Excel通用类,但是在实际应用中,可能不是直接导出模型,而是通过Linq查询后获取到最终结果再导出 通用类: public enum DataTypeEnum { Int = , ...

  7. asp.net中导出Excel的方法

    一.asp.net中导出Excel的方法: 本文转载 在asp.net中导出Excel有两种方法,一种是将导出的文件存放在服务器某个文件夹下面,然后将文件地址输出在浏览器上:一种是将文件直接将文件输出 ...

  8. ASP.NET导出excel表方法汇总

    asp.net里导出excel表方法汇总  1.由dataset生成 public void CreateExcel(DataSet ds,string typeid,string FileName) ...

  9. 懒人小工具:自动生成Model,Insert,Select,Delete以及导出Excel的方法

    在开发的过程中,我们为了节约时间,往往会将大量重复机械的代码封装,考虑代码的复用性,这样我们可以节约很多时间来做别的事情.最近跳槽到一节webform开发的公司,主要是开发自己公司用的ERP.开始因为 ...

随机推荐

  1. Eclipse 常用快捷键 (动画讲解)(转载)

    http://www.cnblogs.com/TankXiao/p/4018219.html#fix 很详细呀/

  2. 关于Storyboard

    界面的搭建器IB有两种 1.stroyboard (不仅可以搭建界面 并且可以实现界面之间的关系) 2.xib (只能是单个视图或者界面) 如何配置自己创建的storyboard 1.infoPlis ...

  3. windows系统下搭建Python开发环境

    1.首先下载最新的Python http://www.python.org/download/,我下载的是最新的Python3.5.1 2.下载完成之后开始安装,安装就比较简单了,一路下一步. 3.安 ...

  4. Java并发编程之ThreadLocal类

    ThreadLocal类可以理解为ThreadLocalVariable(线程局部变量),提供了get与set等访问接口或方法,这些方法为每个使用该变量的线程都存有一份独立的副本,因此get总是返回当 ...

  5. MFC CSplitterWnd的用法

    用MFC开发一个软件界面中需要拆分多个试图窗口时,使用CSplitterWnd类  CSplitterWnd类主要用在创建一个拆分试图窗口.通常嵌入在框架窗口中(CMainFrame) 创建步骤: 1 ...

  6. 解决在IE浏览器下 boder边框出现断裂或虚线的问题

    ie6.0下面经常会出现border边框断断续续的问题,等深一步了解了div之后自然会经常碰到这种问题了,不过初学div+css 的一般不会用遇到这个问题,因为初学者不会偷懒,等我们觉得用的很熟了,各 ...

  7. Android 使用BroadcastReceiver的几种方法

    发送自定义广播 全局广播 发送标准广播 1.定义广播接收器.(在发送广播前,需要先定义一个广播接收器,不然发了也是白发) public class MyBroadcastReceiver extend ...

  8. canvas认识

    1使用canvas绘制一个矩形 <canvas id="canvas" width="640" height="360">< ...

  9. 求绝对值,hdu-2003

    求绝对值 Problem Description 求实数的绝对值.   Input 输入数据有多组,每组占一行,每行包含一个实数.   Output 对于每组输入数据,输出它的绝对值,要求每组数据输出 ...

  10. humble number(hd1058)

    Problem Description A number whose only prime factors are 2,3,5 or 7 is called a humble number. The ...