/// <summary>
/// NPOI导出帮助类
/// </summary>
public class NPOIHelper
{
/// <summary>
/// DataTable导出到Excel的MemoryStream
/// </summary>
/// <param name="dt">源DataTable</param>
/// <param name="dicTableHeader">表头文本</param>
private static MemoryStream Export(DataTable dt, Dictionary<string, string> dicTableHeader)
{
HSSFWorkbook workbook = new HSSFWorkbook();
ISheet sheet = workbook.CreateSheet("工作表1"); IRow headerRow = sheet.CreateRow();
int headerIndex = ; ICellStyle headerCellStyle = Getcellstyle(workbook, stylexls.头);
ICellStyle dateCellStyle = Getcellstyle(workbook, stylexls.时间); foreach (var item in dicTableHeader)
{
ICell cell = headerRow.CreateCell(headerIndex);
cell.CellStyle = headerCellStyle;
cell.SetCellValue(item.Value);
headerIndex = headerIndex + ;
}
sheet.CreateFreezePane(, , , ); int rowCount = dt.Rows.Count;
for (int i = ; i < rowCount; i++)
{
IRow row = sheet.CreateRow(i + );
int rowIndex = ;
foreach (var item in dicTableHeader)
{
ICell newCell = row.CreateCell(rowIndex);
rowIndex = rowIndex + ;
DataColumn dc = dt.Columns[item.Key];
string drValue = dt.Rows[i][item.Key].ToString();
switch (dc.DataType.ToString())
{
case "System.String"://字符串类型
newCell.SetCellValue(drValue);
break;
case "System.DateTime"://日期类型
DateTime dateV;
DateTime.TryParse(drValue, out dateV);
newCell.SetCellValue(dateV); newCell.CellStyle = dateCellStyle;//格式化显示
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("");
break;
}
}
}
////自动列宽
//for (int i = 0; i <= dicTableHeader.Count; i++)
// sheet.AutoSizeColumn(i, true); using (MemoryStream ms = new MemoryStream())
{
workbook.Write(ms);
ms.Flush();
ms.Position = ;
return ms;
}
} /// <summary>
/// DataTable导出到Excel的MemoryStream
/// </summary>
/// <param name="dt">数据源DataTable</param>
/// <param name="heardList">头部列表</param>
/// <returns></returns>
private static MemoryStream Export(DataTable dt, IList<SYS_DICT> heardList)
{
HSSFWorkbook workbook = new HSSFWorkbook();
ISheet sheet = workbook.CreateSheet("工作表1"); ICellStyle headerCellStyle = Getcellstyle(workbook, stylexls.头);
ICellStyle dateCellStyle = Getcellstyle(workbook, stylexls.时间); IRow headerRow = sheet.CreateRow();
int headerIndex = ;
foreach (var item in heardList)
{
ICell cell = headerRow.CreateCell(headerIndex);
cell.CellStyle = headerCellStyle;
cell.SetCellValue(item.fname_ch);
headerIndex = headerIndex + ;
}
sheet.CreateFreezePane(, , , ); int rowCount = dt.Rows.Count;
for (int i = ; i < rowCount; i++)
{
IRow row = sheet.CreateRow(i + );
int rowIndex = ;
foreach (var item in heardList)
{
ICell newCell = row.CreateCell(rowIndex);
rowIndex = rowIndex + ;
DataColumn dc = dt.Columns[item.field_name];
string drValue = dt.Rows[i][item.field_name].ToString();
switch (dc.DataType.ToString())
{
case "System.String"://字符串类型
newCell.SetCellValue(drValue);
break;
case "System.DateTime"://日期类型
DateTime dateV;
DateTime.TryParse(drValue, out dateV);
newCell.SetCellValue(dateV); newCell.CellStyle = dateCellStyle;//格式化显示
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("");
break;
}
}
}
////自动列宽
//for (int i = 0; i <= dicTableHeader.Count; i++)
// sheet.AutoSizeColumn(i, true); int heardListLen = heardList.Count;
for (int i = ; i < heardListLen; i++)
{
int width = ;
int.TryParse(heardList[i].ExcelColWidth.ToString(), out width);
width = (int)((width + 0.72) * );
sheet.SetColumnWidth(i, width);
} using (MemoryStream ms = new MemoryStream())
{
workbook.Write(ms);
ms.Flush();
ms.Position = ;
return ms;
}
} /// <summary>
/// 用于Web导出
/// </summary>
/// <param name="dt">数据源DataTable</param>
/// <param name="strFileName">文件名</param>
/// <param name="dicTableHeader">导出对照</param>
public static void ExportByWeb(DataTable dt, string strFileName, Dictionary<string, string> dicTableHeader)
{
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(Export(dt, dicTableHeader).GetBuffer());
curContext.Response.End();
} /// <summary>
/// Web Excel导出
/// </summary>
/// <param name="dt">数据源DataTable</param>
/// <param name="strFileName">文件名</param>
/// <param name="heardList">头部列表</param>
public static void ExportByWeb(DataTable dt, string strFileName, IList<SYS_DICT> heardList)
{
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(Export(dt, heardList).GetBuffer());
curContext.Response.End();
} #region 定义单元格常用到样式的枚举
public enum stylexls
{
头,
url,
时间,
数字,
钱,
百分比,
中文大写,
科学计数法,
默认
}
#endregion #region 定义单元格常用到样式
private static ICellStyle Getcellstyle(IWorkbook wb, stylexls str)
{
ICellStyle cellStyle = wb.CreateCellStyle(); //定义几种字体
//也可以一种字体,写一些公共属性,然后在下面需要时加特殊的
IFont font12 = wb.CreateFont();
font12.FontHeightInPoints = ;
font12.FontName = "微软雅黑"; IFont headerFont = wb.CreateFont();
headerFont.FontHeightInPoints = ;
headerFont.IsBold = true;
headerFont.FontName = "微软雅黑"; IFont font = wb.CreateFont();
font.FontName = "微软雅黑";
//font.Underline = 1;下划线 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.FillBackgroundColor = HSSFColor.OLIVE_GREEN.BLUE.index;
//cellStyle.FillForegroundColor = HSSFColor.OLIVE_GREEN.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 = ; //上面基本都是设共公的设置
//下面列出了常用的字段类型
switch (str)
{
case stylexls.头:
cellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
// cellStyle.FillPattern = FillPatternType.LEAST_DOTS;
cellStyle.SetFont(headerFont);
break;
case stylexls.时间:
IDataFormat datastyle = wb.CreateDataFormat(); cellStyle.DataFormat = datastyle.GetFormat("yyyy-MM-dd HH:mm:ss");
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
}

NPOI帮助类的更多相关文章

  1. NET npoi帮助类

    nuget添加npoi /// <summary> /// npoi帮助类 /// </summary> public static class NpoiHelper { // ...

  2. NPOI 帮助类

    NPOI 帮助类 代码实现了来自于互联网 using System; using System.Data; using System.IO; using System.Text; using NPOI ...

  3. NPOI Excel类

    using System;using System.Collections.Generic;using System.Linq;using System.Text;using NPOI.HSSF.Us ...

  4. NPOI操作类

    using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Secu ...

  5. NPOI帮助类(Excel转DataTable、DataTable转Excel)

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using NPOI.SS. ...

  6. NPOI工具类

    NPOI调用方法 DataTable dt = new DataTable(); Dictionary<string, string> header = new Dictionary< ...

  7. 免费高效实用的.NET操作Excel组件NPOI(.NET组件介绍之六)

    很多的软件项目几乎都包含着对文档的操作,前面已经介绍过两款操作文档的组件,现在介绍一款文档操作的组件NPOI. NPOI可以生成没有安装在您的服务器上的Microsoft Office套件的Excel ...

  8. 总结一下工作中遇到的NPOI以及在ASP.NET MVC中的使用

    1.前言 相信大家在工作中经常要遇到一些导入导出Execl操作.学习贵在分享,分享使人快乐,园子里的前辈已经有很多好的文章,鄙人也是能力有限,在这里把这些好的文章总结,方便以后再工作中使用. NPOI ...

  9. .NET使用NPOI组件将数据导出Excel

    .NPOI官方网站:http://npoi.codeplex.com/ 可以到此网站上去下载最新的NPOI组件版本 2.NPOI在线学习教程(中文版): http://www.cnblogs.com/ ...

随机推荐

  1. [P1329] 数列

    设F[i,j]为长度为i是,前缀和为j的方案数. [转移] F[i,j] => F[i+1,j+i] F[i,j] => F[i+1,j-i] [原理] 由于A[0]=0,所以有A[1]= ...

  2. Ubuntu 16.04安装sogou 拼音输入法

    一.更换为国内的软件源 安装搜狗输入法之前请先更换为国内的软件源,否则无法解决依赖问题.首先,用以下命令打开源列表: sudo gedit /etc/apt/sources.list #用文本编辑器打 ...

  3. Linux_CentOS-服务器搭建 <三> 补充

    今天 才发现,服务器上 JDK 都没有好好的安装下.在这里补充说下. 1.看看机子上JDK的安装了多少 $ rpm -qa |grep java 会出现类似: java-1.6.0-openjdk-1 ...

  4. Kafka项目实战-用户日志上报实时统计之应用概述

    1.概述 本课程的视频教程地址:<Kafka实战项目之应用概述> 本课程是通过一个用户实时上报日志来展开的,通过介绍 Kafka 的业务和应用场景,并带着大家搭建本 Kafka 项目的实战 ...

  5. springboot json返回null问题处理

    在开发过程中,我们需要统一返回前端json格式的数据,但有些接口的返回值存在 null或者""这种没有意义的字段.以上不仅影响理解,还浪费带宽,这时我们可以统一做一下处理:不返回空 ...

  6. fastdfs集群版搭建(一)- storage集群搭建与统一入口访问

    前言 接着上篇博客:详细的最新版fastdfs单机版搭建,今天来讲讲fastdfs的集群搭建,限于篇幅,今天先搭建stoarge集群,并实现统一的http访问方式: 没看我上篇博客的小伙伴,最好先去瞅 ...

  7. ubantu 安装杀毒软件 clamav

    前言: 搜索了一番安装杀毒软件的教程, 但是多有残缺不全的, 所以整理一下,以作记录 1. 添加用户 groupadd clamav useradd -g clamav -s /bin/false - ...

  8. 一张图读懂PBN旁切转弯计算

    当DOC8168进入PBN章节以后,所有的保护区不再标注风螺旋的字母位置点.似乎ICAO已经有了精确计算的方法,只是没有告诉我们.沿着风螺旋的轨迹一路走来,切线与角度的换算方法想必已经相当熟悉了吧,这 ...

  9. Java与c#的一些细节区别

    实习中用的语言是c#,第一次接触到这种语言,然后写的过程中,发觉和Java几乎一摸一样,好像根本是无缝切换,但细节仍有很大的区别,称有空总结一波里面的部分细节实现. ps. 我写c#过程中,发觉c#有 ...

  10. MySQL 事务机制

    事务处理是保证数据安全的重要机制,事务有四个重要属性 ,根据它们的英文名称可以记为ACID: 原子性(Atomic): 事务操作是不可分割的; 事务只存在已执行和未执行两种状态,不存在只执行了部分指令 ...