using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Web;
using NPOI;
using NPOI.HPSF;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel; namespace System
{
public class NPOIHelper
{ /// <summary>
/// 用于Web导出
/// </summary>
/// <param name="strFileName">文件名</param>
/// <param name="list">todo: describe list parameter on ExportByWeb</param>
/// <param name="titleDic">todo: describe titleDic parameter on ExportByWeb</param>
public static void ExportByWeb<T>(List<T> list, string strFileName, Dictionary<string, string> titleDic)
{
HttpContext curContext = HttpContext.Current; // 设置编码和附件格式
curContext.Response.ContentType = "application/vnd.ms-excel";
curContext.Response.ContentEncoding = Encoding.UTF8;
curContext.Response.Charset = "";
strFileName = strFileName + DateTime.Now.ToString("yyyyMMddHHmmss");
string fileName = HttpUtility.UrlEncode(strFileName, Encoding.UTF8) + ".xls";
curContext.Response.AppendHeader("Content-Disposition",
"attachment;filename=" + fileName); curContext.Response.BinaryWrite(ListToExcel(list, strFileName, titleDic).GetBuffer());
curContext.Response.End();
} /// <summary>
/// List导出到Excel的MemoryStream
/// </summary>
/// <param name="list">需要导出的泛型List</param>
/// <param name="strHeaderText">第一行标题头</param>
/// <param name="titleDictionaries">列名称字典映射</param>
/// <param name="title">todo: describe title parameter on ListToExcel</param>
/// <param name="titleDic">todo: describe titleDic parameter on ListToExcel</param>
/// <returns>内存流</returns>
private static MemoryStream ListToExcel<T>(List<T> list, string strHeaderText = null,
Dictionary<string, string> titleDic = null)
{
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet(); //设置文件属性
SetFileSummary(strHeaderText, workbook); //获取列宽
int[] arrColWidth = GetColumnWidth(titleDic); //日期风格
ICellStyle dateStyle = GetDateStyle(workbook); //Excel标题风格
HSSFCellStyle headStyle = GetHeadStyle(workbook); /*在第一行创建标题行*/
CreateHeadRow(titleDic, sheet, arrColWidth, headStyle); //通过反射得到对象的属性集合
Type type = null;
if (list != null && list.Count > )
{
type = list.First().GetType();
for (int row = ; row < list.Count; row++)
{
HSSFRow dataRow = (HSSFRow)sheet.CreateRow(row + ); int cellIndex = ;
foreach (var dicItem in titleDic)
{
HSSFCell newCell = (HSSFCell)dataRow.CreateCell(cellIndex); string drValue = string.Empty; PropertyInfo propInfo = type.GetProperty(dicItem.Key); var propValue = type.GetProperty(dicItem.Key).GetValue(list[row]);
if (propValue != null)
{
drValue = propValue.ToString();
}
SetCellValueByType(newCell, drValue, propInfo, dateStyle); cellIndex = cellIndex + ;
}
}
} using (MemoryStream ms = new MemoryStream())
{
workbook.Write(ms);
ms.Flush();
ms.Position = ;
workbook.Close();
return ms;
}
} private static void SetCellValueByType(HSSFCell newCell, string drValue, PropertyInfo propInfo, ICellStyle dateStyle)
{
if (string.IsNullOrEmpty(drValue))
{
return;
} string propertyName = GetPropertyFullName(propInfo); switch (propertyName)
{
case "System.String": //字符串类型
newCell.SetCellValue(drValue);
break;
case "System.DateTime": //日期类型
DateTime dateV;
DateTime.TryParse(drValue, out dateV);
newCell.SetCellValue(dateV); newCell.CellStyle = dateStyle; //格式化显示
break;
case "System.Boolean": //布尔型
bool boolV = false;
bool.TryParse(drValue, out boolV);
newCell.SetCellValue(boolV);
break;
case "System.Int16": //整型
case "System.Int32":
case "System.Int64":
case "System.Byte":
int intV = ;
int.TryParse(drValue, out intV);
newCell.SetCellValue(intV);
break;
case "System.Decimal": //浮点型
case "System.Double":
double doubV = ;
double.TryParse(drValue, out doubV);
newCell.SetCellValue(doubV);
break;
case "System.DBNull": //空值处理
newCell.SetCellValue("");
break;
default:
newCell.SetCellValue(drValue);
break;
}
} private static string GetPropertyFullName(PropertyInfo propInfo)
{
var propertyName = propInfo.PropertyType.FullName;
if (propInfo.PropertyType.IsGenericType && propInfo.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
propertyName = propInfo.PropertyType.GetGenericArguments()[].FullName;
} return propertyName;
} public static object GetCellValueByType(ICell cell, PropertyInfo propInfo)
{
if (string.IsNullOrWhiteSpace(cell.ToString()))
{
return string.Empty;
}
if (propInfo.PropertyType.IsEnum)
{
return Enum.Parse(propInfo.PropertyType, cell.ToString());
}
string propertyName = GetPropertyFullName(propInfo);
switch (propertyName)
{
case "System.String": //字符串类型
return cell.ToString();
case "System.DateTime": //日期类型
return cell.DateCellValue;
case "System.Boolean": //布尔型
return cell.BooleanCellValue;
case "System.Int16": //整型
case "System.Int32":
case "System.Int64":
int.TryParse(cell.ToString(), out int value);
return value;
case "System.Byte":
case "System.Decimal": //浮点型
case "System.Double":
return cell.NumericCellValue;
case "System.Single":
return Convert.ToSingle(cell.ToString());
default:
return cell.ToString();
}
} private static void CreateHeadRow(Dictionary<string, string> titleDic, HSSFSheet sheet, int[] arrColWidth, HSSFCellStyle headStyle)
{
HSSFRow headerRow = (HSSFRow)sheet.CreateRow(); int colIndex = ;
foreach (var dicItem in titleDic)
{
string columnName = dicItem.Value;
headerRow.CreateCell(colIndex).SetCellValue(columnName);
headerRow.GetCell(colIndex).CellStyle = headStyle;
//设置列宽
sheet.SetColumnWidth(colIndex, (arrColWidth[colIndex] + ) * );
colIndex++;
}
} private static HSSFCellStyle GetHeadStyle(HSSFWorkbook workbook)
{
HSSFCellStyle headStyle = (HSSFCellStyle)workbook.CreateCellStyle();
HSSFFont font = (HSSFFont)workbook.CreateFont();
font.FontHeightInPoints = ;
font.Boldweight = ;
font.FontName = "宋体";
headStyle.SetFont(font);
headStyle.VerticalAlignment = VerticalAlignment.Center;
headStyle.Alignment = HorizontalAlignment.Center;//水平对齐
return headStyle;
} private static HSSFCellStyle GetDateStyle(HSSFWorkbook workbook)
{
HSSFCellStyle dateStyle = (HSSFCellStyle)workbook.CreateCellStyle();
HSSFDataFormat format = (HSSFDataFormat)workbook.CreateDataFormat();
dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd HH:mm:ss");
return dateStyle;
} /// <summary>
/// 设置文件属性信息
/// </summary>
/// <param name="strHeaderText"></param>
/// <param name="workbook"></param>
private static void SetFileSummary(string strHeaderText, HSSFWorkbook workbook)
{
DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
dsi.Company = "NPOI";
workbook.DocumentSummaryInformation = dsi; SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
si.Author = ""; //填加xls文件作者信息
si.ApplicationName = "管理系统"; //填加xls文件创建程序信息
si.LastAuthor = ""; //填加xls文件最后保存者信息
si.Comments = ""; //填加xls文件作者信息
si.Title = strHeaderText; //填加xls文件标题信息
si.Subject = ""; //填加文件主题信息
si.CreateDateTime = DateTime.Now;
workbook.SummaryInformation = si;
} /// <summary>
/// 获取列宽
/// </summary>
/// <param name="titleDic"></param>
/// <returns></returns>
private static int[] GetColumnWidth(Dictionary<string, string> titleDic)
{
int fieldsCount = titleDic.Count;
int[] arrColWidth = new int[fieldsCount];
int index = ;
foreach (var item in titleDic)
{
arrColWidth[index] = Encoding.GetEncoding().GetBytes(item.Value).Length;
index++;
} return arrColWidth;
}
}
}

NPOI导入导出Excel工具类的更多相关文章

  1. 导入导出Excel工具类ExcelUtil

    前言 前段时间做的分布式集成平台项目中,许多模块都用到了导入导出Excel的功能,于是决定封装一个ExcelUtil类,专门用来处理Excel的导入和导出 本项目的持久化层用的是JPA(底层用hibe ...

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

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

  3. NPOI导入导出EXCEL通用类,可直接使用在WinForm项目中

    由于XSSFWorkbook类型的Write方法限制,Write完成后就自动关闭流数据,所以无法很好的支持的Web模式,网上目前也未找到好的解决方案. 注意:若直接使用在WinForm项目中,必需先下 ...

  4. NPOI导入导出Excel

    .net mvc利用NPOI导入导出excel 注意:如何导出的提交方式ajax导出是失效的! 解决方案是:js处理l两个表单的提交  代码:  第一步. 在页面里面加入2个隐藏的iframe, 如下 ...

  5. javaEE开发之导出excel工具类

    web开发中,一个系统的普通需求也包含导出excel,一般採用POI做统计报表导出excel. 导出excel工具类: import java.io.FileOutputStream; import ...

  6. Java 通过Xml导出Excel文件,Java Excel 导出工具类,Java导出Excel工具类

    Java 通过Xml导出Excel文件,Java Excel 导出工具类,Java导出Excel工具类 ============================== ©Copyright 蕃薯耀 20 ...

  7. .Net core NPOI导入导出Excel

    最近在想.net core NPOI 导入导出Excel,一开始感觉挺简单的,后来真的遇到很多坑.所以还是写一篇博客让其他人少走一些弯路,也方便忘记了再重温一遍.好了,多的不说,直接开始吧. 在.Ne ...

  8. 关于Excel导入导出POI工具类

    import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import ...

  9. MVC NPOI Linq导出Excel通用类

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

随机推荐

  1. 使用awk和sed获取文件奇偶数行的方法总结

    测试文件test.file [root@localhost ~]# cat test.file 111111111111111 222222222222222 333333333333333 4444 ...

  2. 自动生成实体类和xml

    1 首先eclipse需要安装一个插件 2 两个配置文件 1 generator.properties 2 generator.xml <?xml version="1.0" ...

  3. Python异常处理详解

    在shell脚本中,常用if来判断程序的某个部分是否可能会出错,并在if的分支中做出对应的处理,从而让程序更具健壮性.if判断是异常处理的一种方式,所有语言都通用.对于特性完整的编程语言来说,都有专门 ...

  4. JavaScript 系列博客(三)

    JavaScript 系列博客(三) 前言 本篇介绍 JavaScript 中的函数知识. 函数的三种声明方法 function 命令 可以类比为 python 中的 def 关键词. functio ...

  5. eclipse使用svn

    主干(trunk).分支(branch ).标记(tag) 用法示例 + 图解   以svn为例,git的master相当于trunk,dev分支相当于branches --------------- ...

  6. 利用OpenCV给图像添加中文标注

    利用OpenCV给图像添加中文标注 : 参考:http://blog.sina.com.cn/s/blog_6bbd2dd101012dbh.html  和https://blog.csdn.net/ ...

  7. IDEA设置显示中文文档API方法说明

    首先,我们从网上下载好对应的java最新的中文api文档,chm格式的 chm其实相当于一个压缩包,里面有许多html文件 让IDEA显示中文文档,其实原理就是是让IDEA把java的api的对应ht ...

  8. 使用CSS实现无滚动条滚动

    我们都知道,撸页面的时候当我们的内容超出了我们的div,往往会出现滚动条,影响美观. 尤其是当我们在做一些导航菜单的时候.滚动条一出现就破坏了UI效果. 我们不希望出现滚动条,也不希望超出去的内容被放 ...

  9. 4 ;XHTML表格

    1.表格的基本格式 2.<table>标签下的常用属性 3.<table>标签下的边框设置 4.<tr><th><td>标签下的常用属性 5 ...

  10. jQuery中$.ajax()方法参数解析

    本文实例为大家讲解了jQuery $.ajax()方法参数,供大家参考,具体内容如下 $.ajax({ url:'test.do', data:{id:123,name:'xiaoming'}, ty ...