public class NPOIHelper
{
/// <summary>
/// DataTable导出到Excel文件
/// </summary>
/// <param name="dtSource">源DataTable</param>
/// <param name="strHeaderText">表头文本</param>
/// <param name="strFileName">保存位置</param>
public static void ExportByServer(DataTable dtSource, string strHeaderText, string strFileName)
{
using (MemoryStream ms = Export(dtSource, strHeaderText))
{
using (FileStream fs = new FileStream(strFileName, FileMode.Create, FileAccess.Write))
{
byte[] data = ms.ToArray();
fs.Write(data, , data.Length);
fs.Flush();
}
}
} /// <summary>
/// 用于Web导出
/// </summary>
/// <param name="dtSource">源DataTable</param>
/// <param name="strHeaderText">表头文本</param>
/// <param name="strFileName">文件名</param>
public static void ExportByWeb(DataTable dtSource, string strHeaderText, string strFileName)
{
HttpContext curContext = HttpContext.Current; // 设置编码和附件格式
curContext.Response.ContentType = "application/vnd.ms-excel";
curContext.Response.ContentEncoding = Encoding.UTF8;
curContext.Response.Charset = "";
curContext.Response.AppendHeader("Content-Disposition",
"attachment;filename=" + HttpUtility.UrlEncode(strFileName, Encoding.UTF8)); curContext.Response.BinaryWrite(Export(dtSource, strHeaderText).GetBuffer());
curContext.Response.End();
} /// <summary>读取excel
/// 默认第一行为标头
/// </summary>
/// <param name="strFileName">excel文档路径</param>
/// <returns></returns>
public static DataTable Import(string strFileName)
{
DataTable dt = new DataTable(); HSSFWorkbook hssfworkbook;
using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
{
hssfworkbook = new HSSFWorkbook(file);
}
ISheet sheet = hssfworkbook.GetSheetAt();
System.Collections.IEnumerator rows = sheet.GetRowEnumerator(); IRow headerRow = sheet.GetRow();
int cellCount = headerRow.LastCellNum; for (int j = ; j < cellCount; j++)
{
ICell cell = headerRow.GetCell(j);
dt.Columns.Add(cell.ToString());
} for (int i = (sheet.FirstRowNum + ); i <= sheet.LastRowNum; i++)
{
IRow row = sheet.GetRow(i);
DataRow dataRow = dt.NewRow(); for (int j = row.FirstCellNum; j < cellCount; j++)
{
if (row.GetCell(j) != null)
dataRow[j] = row.GetCell(j).ToString();
} dt.Rows.Add(dataRow);
}
return dt;
} /// <summary>
/// DataTable导出到Excel的MemoryStream
/// </summary>
/// <param name="dtSource">源DataTable</param>
/// <param name="strHeaderText">表头文本</param>
public static MemoryStream Export(DataTable dtSource, string strHeaderText)
{
HSSFWorkbook workbook = new HSSFWorkbook();
ISheet sheet = workbook.CreateSheet(); #region 右击文件 属性信息
{
DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
dsi.Company = "Sohu";
workbook.DocumentSummaryInformation = dsi; SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
si.Author = "文件作者信息"; //填加xls文件作者信息
si.ApplicationName = "创建程序信息"; //填加xls文件创建程序信息
si.LastAuthor = "最后保存者信息"; //填加xls文件最后保存者信息
si.Comments = "作者信息"; //填加xls文件作者信息
si.Title = "标题信息"; //填加xls文件标题信息
si.Subject = "主题信息";//填加文件主题信息
si.CreateDateTime = DateTime.Now;
workbook.SummaryInformation = si;
}
#endregion ICellStyle dateStyle = workbook.CreateCellStyle();
IDataFormat format = workbook.CreateDataFormat();
dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd"); //取得列宽
int[] arrColWidth = new int[dtSource.Columns.Count];
foreach (DataColumn item in dtSource.Columns)
{
arrColWidth[item.Ordinal] = Encoding.GetEncoding().GetBytes(item.ColumnName.ToString()).Length;
}
for (int i = ; i < dtSource.Rows.Count; i++)
{
for (int j = ; j < dtSource.Columns.Count; j++)
{
int intTemp = Encoding.GetEncoding().GetBytes(dtSource.Rows[i][j].ToString()).Length;
if (intTemp > arrColWidth[j])
{
arrColWidth[j] = intTemp;
}
}
}
int rowIndex = ;
foreach (DataRow row in dtSource.Rows)
{
#region 新建表,填充表头,填充列头,样式
if (rowIndex == || rowIndex == )
{
if (rowIndex != )
{
sheet = workbook.CreateSheet();
} #region 表头及样式
{
IRow headerRow = sheet.CreateRow();
headerRow.HeightInPoints = ;
headerRow.CreateCell().SetCellValue(strHeaderText); ICellStyle headStyle = workbook.CreateCellStyle();
headStyle.Alignment = HorizontalAlignment.Center;
IFont font = workbook.CreateFont();
font.FontHeightInPoints = ;
font.Boldweight = ;
headStyle.SetFont(font);
headerRow.GetCell().CellStyle = headStyle;
sheet.AddMergedRegion(new CellRangeAddress(, , , dtSource.Columns.Count - )); }
#endregion #region 列头及样式
{
IRow headerRow = sheet.CreateRow(); ICellStyle headStyle = workbook.CreateCellStyle();
headStyle.Alignment = HorizontalAlignment.Center; IFont font = workbook.CreateFont();
font.FontHeightInPoints = ;
font.Boldweight = ;
headStyle.SetFont(font);
foreach (DataColumn column in dtSource.Columns)
{
headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
headerRow.GetCell(column.Ordinal).CellStyle = headStyle; //设置列宽
sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + ) * );
} }
#endregion rowIndex = ;
}
#endregion #region 填充内容
IRow dataRow = sheet.CreateRow(rowIndex);
foreach (DataColumn column in dtSource.Columns)
{
ICell newCell = dataRow.CreateCell(column.Ordinal); string drValue = row[column].ToString(); switch (column.DataType.ToString())
{
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("");
break;
} }
#endregion rowIndex++;
}
using (MemoryStream ms = new MemoryStream())
{
workbook.Write(ms);
ms.Flush();
ms.Position = ; //sheet.Dispose();
//workbook.Dispose();//一般只用写这一个就OK了,他会遍历并释放所有资源,但当前版本有问题所以只释放sheet
return ms;
}
} /// <summary>
/// DataTable按模板导出到Excel文件
/// </summary>
/// <param name="dtSource">源DataTable</param>
/// <param name="TempletFileName">模板文件</param>
/// <param name="strFileName">保存位置</param>
public static void ExportByTemplate(string TempletFileName, string strFileName, DataTable dt, string Type)
{
using (MemoryStream ms = ExportByTemp(TempletFileName, dt, Type))
{
using (FileStream fs = new FileStream(strFileName, FileMode.Create, FileAccess.Write))
{
byte[] data = ms.ToArray();
fs.Write(data, , data.Length);
fs.Flush();
}
}
}
/// <summary>
/// DataTable导出到Excel的MemoryStream
/// </summary>
/// <param name="dt">数据源</param>
/// <param name="TempletFileName">Excel模板</param>
/// <returns></returns>
public static MemoryStream ExportByTemp(string TempletFileName, DataTable dt,string Type)
{
FileStream file = new FileStream(TempletFileName, FileMode.Open, FileAccess.Read); HSSFWorkbook workbook = new HSSFWorkbook(file);
ISheet sheet = workbook.GetSheetAt(); //ICellStyle dateStyle = workbook.CreateCellStyle();
//dateStyle.BorderBottom = BorderStyle.Thin;
//dateStyle.BorderLeft = BorderStyle.Thin;
//dateStyle.BorderRight = BorderStyle.Thin;
//dateStyle.BorderTop = BorderStyle.Thin; int rowIndex = ; foreach (DataRow entity in dt.Rows)
{
IRow dataRow = sheet.CreateRow(rowIndex); if (Type.Equals("SaleType"))
{
ICell newCell0 = dataRow.CreateCell();
newCell0.SetCellValue(entity[].ToString());
//newCell0.CellStyle = dateStyle;
}
else {
ICell newCell0 = dataRow.CreateCell();
newCell0.SetCellValue(entity[].ToString());
//newCell0.CellStyle = dateStyle;
}
//ICell newCell7 = dataRow.CreateCell(7);
//if (type.Equals("excel"))
//{
// newCell7.SetCellValue(entity.Location == "" ? "" : "第" + entity.Location + "行");
//}
//else if (type.Equals("word"))
//{
// newCell7.SetCellValue(entity.Location == "" ? "" : "第" + entity.Location + "页");
//}
//newCell7.CellStyle = dateStyle; rowIndex++;
}
if (dt.Rows.Count == )
{
IRow dataRow = sheet.CreateRow(rowIndex);
ICell newCelllast = dataRow.CreateCell();
newCelllast.SetCellValue(" ");
} using (MemoryStream ms = new MemoryStream())
{
workbook.Write(ms);
ms.Flush();
ms.Position = ; //sheet.Dispose();
//workbook.Dispose();//一般只用写这一个就OK了,他会遍历并释放所有资源,但当前版本有问题所以只释放sheet
return ms;
}
} public static void ExportByNodeData(string TfileName, string StrfileName, DataTable dt, string Type,double Rate)
{
using (MemoryStream ms = ExportByNode(TfileName, dt, Type,Rate))
{
using (FileStream fs = new FileStream(StrfileName, FileMode.Create, FileAccess.Write))
{
byte[] data = ms.ToArray();
fs.Write(data, , data.Length);
fs.Flush();
}
}
}
public static MemoryStream ExportByNode(string TempletFileName, DataTable dt, string Type, double Rate)
{
FileStream file = new FileStream(TempletFileName, FileMode.Open, FileAccess.Read); HSSFWorkbook workbook = new HSSFWorkbook(file);
ISheet sheet = workbook.GetSheetAt(); ICellStyle dateStyle = workbook.CreateCellStyle();
dateStyle.BorderBottom = BorderStyle.Thin;
dateStyle.BorderLeft = BorderStyle.Thin;
dateStyle.BorderRight = BorderStyle.Thin;
dateStyle.BorderTop = BorderStyle.Thin; int rowIndex = ; foreach (DataRow entity in dt.Rows)
{
IRow dataRow = sheet.CreateRow(rowIndex); if (Type.Equals("SaleTypeExport"))
{
ICell newCell0 = dataRow.CreateCell();
newCell0.SetCellValue(rowIndex);
newCell0.CellStyle = dateStyle; ICell newCell1 = dataRow.CreateCell();
newCell1.SetCellValue(entity["new_nodename"].ToString());
newCell1.CellStyle = dateStyle; ICell newCell2 = dataRow.CreateCell();
newCell2.SetCellValue(Convert.ToDouble(entity["new_lastyear_total"].ToString()));
newCell2.CellStyle = dateStyle; ICell newCell3 = dataRow.CreateCell();
newCell3.SetCellValue(Convert.ToDouble(entity["new_total_assign2me"].ToString()));
newCell3.CellStyle = dateStyle; ICell newCell4 = dataRow.CreateCell();
newCell4.SetCellValue(Convert.ToInt32(entity["new_accountadd"].ToString()));
newCell4.CellStyle = dateStyle; ICell newCell5 = dataRow.CreateCell();
newCell5.SetCellValue(Convert.ToDouble(entity["new_total_assign2me"].ToString()) - (Convert.ToDouble(entity["new_total_assign2me"].ToString()) * Rate));
newCell5.CellStyle = dateStyle; ICell newCell6 = dataRow.CreateCell();
newCell6.SetCellValue((Convert.ToDouble(entity["new_total_assign2me"].ToString()) * Rate));
newCell6.CellStyle = dateStyle; ICell newCell7 = dataRow.CreateCell();
newCell7.SetCellValue(Convert.ToDouble(entity["RefeAmount"].ToString()));
newCell7.CellStyle = dateStyle; ICell newCell8 = dataRow.CreateCell();
newCell8.SetCellValue(entity["new_description"].ToString());
newCell8.CellStyle = dateStyle;
}
else if (Type.Equals("AccountTypeExport"))
{
ICell newCell0 = dataRow.CreateCell();
newCell0.SetCellValue(rowIndex);
newCell0.CellStyle = dateStyle; ICell newCell1 = dataRow.CreateCell();
newCell1.SetCellValue(entity["new_name"].ToString());
newCell1.CellStyle = dateStyle; ICell newCell2 = dataRow.CreateCell();
newCell2.SetCellValue(Convert.ToDouble(entity["new_lastyear_total"].ToString()));
newCell2.CellStyle = dateStyle; ICell newCell3 = dataRow.CreateCell();
newCell3.SetCellValue(Convert.ToDouble(entity["new_nodetemdesc_amount"].ToString()));
newCell3.CellStyle = dateStyle; ICell newCell4 = dataRow.CreateCell();
newCell4.SetCellValue(Convert.ToDouble(entity["new_nodetemdesc_amount"].ToString()) - (Convert.ToDouble(entity["new_nodetemdesc_amount"].ToString()) * Rate));
newCell4.CellStyle = dateStyle; ICell newCell5 = dataRow.CreateCell();
newCell5.SetCellValue((Convert.ToDouble(entity["new_nodetemdesc_amount"].ToString()) * Rate));
newCell5.CellStyle = dateStyle; ICell newCell6 = dataRow.CreateCell();
newCell6.SetCellValue(Convert.ToDouble(entity["RefeAmount"].ToString()));
newCell6.CellStyle = dateStyle; ICell newCell7 = dataRow.CreateCell();
newCell7.SetCellValue(entity["new_nodetemdesc_description"].ToString());
newCell7.CellStyle = dateStyle;
}
else if (Type.Equals("NodeDescByAccountExport"))
{
ICell newCell0 = dataRow.CreateCell();
newCell0.SetCellValue(rowIndex);
newCell0.CellStyle = dateStyle; ICell newCell1 = dataRow.CreateCell();
newCell1.SetCellValue(entity["new_name"].ToString());
newCell1.CellStyle = dateStyle; ICell newCell2 = dataRow.CreateCell();
newCell2.SetCellValue(Convert.ToDouble(entity["new_nodetemdesc_amount"].ToString()));
newCell2.CellStyle = dateStyle; ICell newCell3 = dataRow.CreateCell();
newCell3.SetCellValue(Convert.ToDouble(entity["new_nodetemdesc_amount"].ToString()) - (Convert.ToDouble(entity["new_nodetemdesc_amount"].ToString()) * Rate));
newCell3.CellStyle = dateStyle; ICell newCell4 = dataRow.CreateCell();
newCell4.SetCellValue((Convert.ToDouble(entity["new_nodetemdesc_amount"].ToString()) * Rate));
newCell4.CellStyle = dateStyle; ICell newCell5 = dataRow.CreateCell();
newCell5.SetCellValue(Convert.ToDouble(entity["RefeAmount"].ToString()));
newCell5.CellStyle = dateStyle; ICell newCell6 = dataRow.CreateCell();
newCell6.SetCellValue(entity["new_nodetemdesc_description"].ToString());
newCell6.CellStyle = dateStyle;
}
else if (Type.Equals("NodeDescBySaleExport"))
{
ICell newCell0 = dataRow.CreateCell();
newCell0.SetCellValue(rowIndex);
newCell0.CellStyle = dateStyle; ICell newCell1 = dataRow.CreateCell();
newCell1.SetCellValue(entity["new_name"].ToString());
newCell1.CellStyle = dateStyle; ICell newCell2 = dataRow.CreateCell();
newCell2.SetCellValue(Convert.ToDouble(entity["new_distributeamount"].ToString()));
newCell2.CellStyle = dateStyle; ICell newCell3 = dataRow.CreateCell();
newCell3.SetCellValue(Convert.ToDouble(entity["new_distributeamount"].ToString()) - (Convert.ToDouble(entity["new_distributeamount"].ToString()) * Rate));
newCell3.CellStyle = dateStyle; ICell newCell4 = dataRow.CreateCell();
newCell4.SetCellValue((Convert.ToDouble(entity["new_distributeamount"].ToString()) * Rate));
newCell4.CellStyle = dateStyle; ICell newCell5 = dataRow.CreateCell();
newCell5.SetCellValue(Convert.ToDouble(entity["RefeAmount"].ToString()));
newCell5.CellStyle = dateStyle; ICell newCell6 = dataRow.CreateCell();
newCell6.SetCellValue(entity["new_description"].ToString());
newCell6.CellStyle = dateStyle;
}
rowIndex++;
} using (MemoryStream ms = new MemoryStream())
{
workbook.Write(ms);
ms.Flush();
ms.Position = ; //sheet.Dispose();
//workbook.Dispose();//一般只用写这一个就OK了,他会遍历并释放所有资源,但当前版本有问题所以只释放sheet
return ms;
}
} }

NPOI常用功能工具类的更多相关文章

  1. Android常用的工具类

    主要介绍总结的Android开发中常用的工具类,大部分同样适用于Java.目前包括HttpUtils.DownloadManagerPro.ShellUtils.PackageUtils. Prefe ...

  2. Android常用的工具类(转)

    主要介绍总结的Android开发中常用的工具类,大部分同样适用于Java.目前包括HttpUtils.DownloadManagerPro.ShellUtils.PackageUtils.Prefer ...

  3. 2013最新Android常用的工具类整理

    主要介绍总结的Android开发中常用的工具类,大部分同样适用于Java. 目前包括HttpUtils.DownloadManagerPro.ShellUtils.PackageUtils. Pref ...

  4. Java语言Lang包下常用的工具类介绍_java - JAVA

    文章来源:嗨学网 敏而好学论坛www.piaodoo.com 欢迎大家相互学习 无论你在开发哪中 Java 应用程序,都免不了要写很多工具类/工具函数.你可知道,有很多现成的工具类可用,并且代码质量都 ...

  5. commons-collections包中的常用的工具类

    commons-collections包中的常用的工具类 <dependency> <groupId>commons-collections</groupId> & ...

  6. Android开发之常用必备工具类图片bitmap转成字符串string与String字符串转换为bitmap图片格式

    作者:程序员小冰,CSDN博客:http://blog.csdn.net/qq_21376985 QQ986945193 博客园主页:http://www.cnblogs.com/mcxiaobing ...

  7. Java,面试题,简历,Linux,大数据,常用开发工具类,API文档,电子书,各种思维导图资源,百度网盘资源,BBS论坛系统 ERP管理系统 OA办公自动化管理系统 车辆管理系统 各种后台管理系统

    Java,面试题,简历,Linux,大数据,常用开发工具类,API文档,电子书,各种思维导图资源,百度网盘资源BBS论坛系统 ERP管理系统 OA办公自动化管理系统 车辆管理系统 家庭理财系统 各种后 ...

  8. Hutool中那些常用的工具类和方法

    Hutool中那些常用的工具类和方法 Hutool是一个Java工具包,它帮助我们简化每一行代码,避免重复造轮子.如果你有需要用到某些工具方法的时候,不妨在Hutool里面找找,可能就有.本文将对Hu ...

  9. java中常用的工具类(三)

    继续分享java中常用的一些工具类.前两篇的文章中有人评论使用Apache 的lang包和IO包,或者Google的Guava库.后续的我会加上的!谢谢支持IT江湖 一.连接数据库的综合类       ...

随机推荐

  1. SpringMVC与Struts2配置区别

     Spring MVC模型与Struts2模型应用:  Html表单: 上述这两段代码无论是SpringMVC还是Struts2,都可以共用.而在请求响应处理类(也就是Controller)上的设计差 ...

  2. ASP获取当前页面带参数的网址(URL地址)的方法

    '获取当前Url参数的函数 Function GetUrl() Dim ScriptAddress,Servername,qs ScriptAddress = CStr(Request.ServerV ...

  3. Could not find artifact com.sun:tools:jar:1.5.0解决方法

    可以参照在XP系统下搭建maven环境出的问题 Unable to locate the Javac Compiler in: C:\Program Files\Java\jre6\..\lib\to ...

  4. Drbd 安装配置

    一.Drbd介绍 Distributed Replicated Block Device(DRBD)是基于块设备在不同的高可用服务器之间同步和镜像数据的软件,通过它可以实现在网络中两台服务器这间基于块 ...

  5. Android logcat使用

    Android logcat使用 1. Android日志说明 当Android系统运行的时候,会搜集所有的系统信息. logcat是Android系统的一个命令行工具,主要用来查看和过滤日志信息. ...

  6. Git和CocoaPods的简单使用

    Git是一款免费.开源的分布式版本控制系统,还有一种SVN的开源的集中式版本控制系统.分布式相比于集中式的最大区别在于开发者可以提交到本地,每个开发者通过克隆(git clone),在本地机器上拷贝一 ...

  7. windows phone 生产二维码和解码本地二维码图片

    前面模仿着写了一个手机扫描二维码和条形码的例子,zxing(下载)的Silverlight库实现的,当时还纳闷有windows phone的库为什么不用,其实都是一样的,,,要改的就是获取摄像头获取的 ...

  8. jquery 动态添加下拉框 需要增加 煊染 selectmenu("refresh");

    若通过js动态选择下拉框的值必须刷新下拉框,例如:var selArray = $("select#sel");selArray[0].selectedIndex = 1;selA ...

  9. poj 3783 Balls 动态规划 100层楼投鸡蛋问题

    作者:jostree 转载请注明出处 http://www.cnblogs.com/jostree/p/4098409.html 题目链接:poj 3783 Balls 动态规划 100层楼投鸡蛋问题 ...

  10. CentOS下Apache+SVN+LDAP的安装与配置

    上班接近4个月了,在公司做配置管理工程师,主要是在Linux下对公司的源代码以及项目发布进行管理.4个月接触了好多新知识,也对各种工具的集成使用搞得云里来雾里去的,所以打算自己搭建一套环境,进行测试. ...