NPOI导入导出Excel工具类
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工具类的更多相关文章
- 导入导出Excel工具类ExcelUtil
前言 前段时间做的分布式集成平台项目中,许多模块都用到了导入导出Excel的功能,于是决定封装一个ExcelUtil类,专门用来处理Excel的导入和导出 本项目的持久化层用的是JPA(底层用hibe ...
- NPOI导入导出EXCEL通用类,供参考,可直接使用在WinForm项目中
以下是NPOI导入导出EXCEL通用类,是在别人的代码上进行优化的,兼容xls与xlsx文件格式,供参考,可直接使用在WinForm项目中,由于XSSFWorkbook类型的Write方法限制,Wri ...
- NPOI导入导出EXCEL通用类,可直接使用在WinForm项目中
由于XSSFWorkbook类型的Write方法限制,Write完成后就自动关闭流数据,所以无法很好的支持的Web模式,网上目前也未找到好的解决方案. 注意:若直接使用在WinForm项目中,必需先下 ...
- NPOI导入导出Excel
.net mvc利用NPOI导入导出excel 注意:如何导出的提交方式ajax导出是失效的! 解决方案是:js处理l两个表单的提交 代码: 第一步. 在页面里面加入2个隐藏的iframe, 如下 ...
- javaEE开发之导出excel工具类
web开发中,一个系统的普通需求也包含导出excel,一般採用POI做统计报表导出excel. 导出excel工具类: import java.io.FileOutputStream; import ...
- Java 通过Xml导出Excel文件,Java Excel 导出工具类,Java导出Excel工具类
Java 通过Xml导出Excel文件,Java Excel 导出工具类,Java导出Excel工具类 ============================== ©Copyright 蕃薯耀 20 ...
- .Net core NPOI导入导出Excel
最近在想.net core NPOI 导入导出Excel,一开始感觉挺简单的,后来真的遇到很多坑.所以还是写一篇博客让其他人少走一些弯路,也方便忘记了再重温一遍.好了,多的不说,直接开始吧. 在.Ne ...
- 关于Excel导入导出POI工具类
import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import ...
- MVC NPOI Linq导出Excel通用类
之前写了一个模型导出Excel通用类,但是在实际应用中,可能不是直接导出模型,而是通过Linq查询后获取到最终结果再导出 通用类: public enum DataTypeEnum { Int = , ...
随机推荐
- docker 构建 https 私有仓库 Registry
1.安装docker # docker install docker 2.拉取仓库镜像 # docker pull registry 3.生成认证certificate # mkdir ~/certs ...
- centos7安装遇到的坑
1.安装中遇到what is the location of the gcc program on your machine 直接输入 no.意思就是跳过gcc的安装了.但是系统虽然安装了vmware ...
- Nacos系列:欢迎来到Nacos的世界!
什么是Nacos? Nacos 是构建以"服务"为中心的现代应用架构 (例如微服务范式.云原生范式) 的服务基础设施. Nacos可以做什么? 1.动态配置服务:支持以中心化.外部 ...
- QT 完美实现圆形按钮
QT 版本:5.6.0 官方的按钮有些普通,如果我们想要换成自己喜欢的按钮而却无从下手,那么请继续往下阅读(皮一下). 首先,可以在网络上搜索一下自己喜欢的按钮图形(或者可以自行绘制),我以下面的图形 ...
- 第一册:lesson ninety-five。
原文: tickets,please. Two return tickets to London please. What time will the next train leave? At nin ...
- 第一册:lesson forty
原文: Penny's bag. A:Is that bag heavy,Penny? B:Not very. A:Here. Put it on this chair. What's in it? ...
- curl模拟请求常用参数
封装一个curl模拟浏览器请求的函数,如下: /** * curl模拟浏览器请求 * @param unknown $url 请求的地址 * @param array $params 请求地址所需要的 ...
- 4.4 explain 之 possible_keys 、key、key_len
一.possible_keys 显示可能应用在这张表中的索引,一个或多个. 查询涉及到的字段上若存在索引,则该索引将被列出,但不一定被查询实际使用. 二.key 实际使用的索引.如果为null,则没有 ...
- 【Java每日一题】20170315
20170314问题解析请点击今日问题下方的“[Java每日一题]20170315”查看(问题解析在公众号首发,公众号ID:weknow619) package Mar2017; public cla ...
- Docker多步构建更小的Java镜像
译者按: 最新版Docker将支持多步构建(Multi-stage build),这样使用单个Dockerfile就可以定义多个中间镜像用于构建,测试以及发布等多个步骤,并且有效减小最终镜像的大小. ...