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 = , ...
随机推荐
- 痞子衡嵌入式:SEGGER J-Link仿真器硬件版本变迁
大家好,我是痞子衡,是正经搞技术的痞子.今天痞子衡给大家介绍的是J-Link仿真器版本变迁. 硬件版本 主控芯片 固件升级工具 V7 ARM7TDMI, 55MHz Atmel AT91SAM7S64 ...
- Go 标准库 http.FileServer 实现静态文件服务
http.FileServer 方法属于标准库 net/http,返回一个使用 FileSystem 接口 root 提供文件访问服务的 HTTP 处理器.可以方便的实现静态文件服务器. http.L ...
- MySQL中间件之ProxySQL(15):ProxySQL代理MySQL组复制
返回ProxySQL系列文章:http://www.cnblogs.com/f-ck-need-u/p/7586194.html 1.ProxySQL+组复制前言 在以前的ProxySQL版本中,要支 ...
- python模块之pickle、shelve、json
一 什么是序列化 序列化指的是将内存中的数据结构转化为一种中间格式,并存储到硬盘上. (反序列化:将硬盘上存储的中间格式数据再还原为内存中的数据结构) 二 为什么要序列化 持久保持状态 需知一个软件/ ...
- 《C#并发编程经典实例》学习笔记—2.1 暂停一段时间
问题: 需要让程序(以异步方式)等待一段时间. 解决方案:Task类的静态函数Delay,返回Task对象 在github开源项目dotnet/coreclr,找到Task.cs有关Delay方法的源 ...
- 结构型---享元模式(Flyweight Pattern)
引言 在软件开发过程,如果我们需要重复使用某个对象的时候,如果我们重复地使用new创建这个对象的话,这样我们在内存就需要多次地去申请内存空间了,这样可能会出现内存使用越来越多的情况,这样的问题是非常严 ...
- Mac下安装最新版本的Graphviz
由于版本兼容问题,Mac下Graphviz之前一直装的是低版本的2.36.高版本的安装方法如下: 1.log in & download Xcode an Xcode Command Line ...
- MySQL技巧(三)运算符与函数
- JS中将变量转为字符串
译者按: 语言的细枝末节了解一下就可以了,不需要太较真,不过如果一点也不知道的话,那就不太妙了. 原文: Converting a value to string in JavaScript 译者: ...
- 如何在Promise链中共享变量?
译者按: 使用Promise写过异步代码的话,会发现在Promise链中共享变量是一个非常头疼的问题,这也是Async/Await胜过Promise的一点,我们在Async/Await替代Promis ...