概述

  NPOI,顾名思义,就是POI的.NET版本。NPOI就是用.NET语言编写的一套数据导出Excel的开源项目,支持XML、xls、xlsx、ppt等格式。.NET不仅实现Excel导出还可以实现Excel导入,读取Excel的数据。

实现

  1、通过nuget,添加NPOI组件1.2以上对应的DLL文件;

  2、编写如下Nopi封装类,该类实现如下功能点

    1> 该类实现数据的超过65535自动分写下一个sheet;

    2> 该类实现Web数据导出和文件保存到本地;

    3> 该类实现Excel文件的读取导出;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Text;
using NPOI;
using NPOI.HPSF;
using NPOI.HSSF;
using NPOI.HSSF.UserModel;
using NPOI.HSSF.Util;
using NPOI.POIFS;
using NPOI.Util;
using System.Data;
using NPOI.SS.UserModel;
using NPOI.SS.Util; namespace DBI.Web.Common
{
public class NpoiHelper
{
/// <summary>
/// DataTable导出到Excel文件
/// </summary>
/// <param name="dtSource">源DataTable</param>
/// <param name="strHeaderText">表头文本</param>
/// <param name="strFileName">保存位置</param>
public static void Export(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>
/// 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(string.IsNullOrWhiteSpace(dtSource.TableName) ? "Sheet1" : dtSource.TableName); #region 右击文件 属性信息 DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
dsi.Company = "NPOI";
workbook.DocumentSummaryInformation = dsi; SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
si.Author = "TCL"; //填加xls文件作者信息
si.ApplicationName = "创建程序信息"; //填加xls文件创建程序信息
si.LastAuthor = "最后保存者信息"; //填加xls文件最后保存者信息
si.Comments = "作者信息"; //填加xls文件作者信息
si.Title = "标题信息"; //填加xls文件标题信息 si.Subject = "主题信息";//填加文件主题信息
si.CreateDateTime = DateTime.Now;
workbook.SummaryInformation = si; #endregion #region 取得列宽,调整宽度 有待优化,如果数据很多,这个地方就会很耗时 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;
}
}
} #endregion var dateStyle = workbook.CreateCellStyle();
var format = workbook.CreateDataFormat();
dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd"); var DataCellStyle = CreateBasicCellStyle(workbook); //计算行数,由于Excel 2003最大条数是65535,超过65535自动创建下一个sheet
int rowIndex = ;
foreach (DataRow row in dtSource.Rows)
{
#region 新建表,填充表头,填充列头,样式
if (rowIndex == || rowIndex == )
{
if (rowIndex != )
{
sheet = workbook.CreateSheet();
} #region 表头及样式
{
var headerRow = sheet.CreateRow();
headerRow.HeightInPoints = ;
headerRow.CreateCell().SetCellValue(strHeaderText); ICellStyle headStyle = workbook.CreateCellStyle();
headStyle.Alignment = HorizontalAlignment.Center;
headStyle.VerticalAlignment = VerticalAlignment.Center;// 上下居中
headStyle.FillForegroundColor = (short); // 设置单元格的背景颜色(单元格的样式会覆盖列或行的样式)
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;
headStyle.VerticalAlignment = VerticalAlignment.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);
newCell.CellStyle = DataCellStyle; 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 = ;
return ms;
}
} /// <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
/// 默认第一行为标头,Exel导出Table数据
/// </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;
} private static HSSFCellStyle CreateBasicCellStyle(HSSFWorkbook workbook)
{
var cellStyle = workbook.CreateCellStyle() as HSSFCellStyle;
cellStyle.BorderLeft = BorderStyle.Thin;
cellStyle.BorderRight = BorderStyle.Thin;
cellStyle.BorderTop = BorderStyle.Thin;
cellStyle.BorderBottom = BorderStyle.Thin;
cellStyle.Alignment = HorizontalAlignment.Center;
cellStyle.VerticalAlignment = VerticalAlignment.Center;
return cellStyle;
}
}
}

参考文档

  NPOI导出Excel表功能实现(多个工作簿)http://www.cnblogs.com/zhengjuzhuan/archive/2010/02/01/1661103.html

  NET使用NPOI组件将数据导出Excel-通用方法  http://www.tuicool.com/articles/eq6FRb

   NET NPOI导出Excel详解    http://www.cnblogs.com/yinrq/p/5590970.html

  基于NPOI的自定义样式报表引擎——ExcelReport  http://www.cnblogs.com/hanzhaoxin/p/4232572.html

基于NPOI导出和导入Excel的更多相关文章

  1. 使用NPOI导出,读取EXCEL(可追加功能)

    使用NPOI导出,读取EXCEL,具有可追加功能 看代码 using System; using System.Collections.Generic; using System.Text; usin ...

  2. NPOI导出数据到Excel

    NPOI导出数据到Excel   前言 Asp.net操作Excel已经是老生长谈的事情了,可下面我说的这个NPOI操作Excel,应该是最好的方案了,没有之一,使用NPOI能够帮助开发者在没有安装微 ...

  3. 原生PHP网页导出和导入excel文件实例

    原生PHP实现的网页导出和导入excel文件实例,包括上传也是用的原生.还可在exportExcel方法里设置字体等表格样式. 导出和导入表单代码: <p style="margin: ...

  4. ASP.NET基于NPOI导出数据

    using System; using System.Collections; using System.Collections.Generic; using System.IO; using Sys ...

  5. C#导出和导入Excel模板功能

    引用  Aspose.Cells; 基于WinForm 导入 private void btn_excel_input_Click(object sender, EventArgs e) { try ...

  6. SpringBoot基于easyexcel导出和写入Excel

      easyexcel是阿里巴巴旗下开源项目,主要用于Excel文件的导入和导出处理,今天我们利用SpringBoot和easyexcel实战演示如何导出和写入Excel文件. 一.加入我们需要的ea ...

  7. JS导出、导入EXCEL(案例)

    插件下载地址:http://oss.sheetjs.com/js-xlsx/xlsx.full.min.js 1.导出excel <!DOCTYPE html> <html> ...

  8. 基于NPOI导出Excel

    在上一篇文章[关于大数据的查询与导出]中,提到了使用NPOI组件导出Excel,本想上次一起分享给大家,无奈最近比较忙,今天抽空整理了下,分享出来. 预置填充模板,并且需要支持公式计算; 可导入图片; ...

  9. 基于NPOI的Execl导入导出例子

    源地址:http://bbs.csdn.net/topics/390830774

随机推荐

  1. decimal与double,float的选择与区别

    decimal 类型可以精确地表示非常大或非常精确的小数.大至 1028(正或负)以及有效位数多达 28 位的数字可以作为 decimal类型存储而不失其精确性.该类型对于必须避免舍入错误的应用程序( ...

  2. Linux中文显示乱码?如何设置centos显示中文

    Linux中文显示乱码?如何设置centos显示中文 怎么设置Linux系统中文语言,这是很多小伙伴在开始使用Linux的时候,都会遇到一个问题,就是终端输入命令回显的时候中文显示乱码.出现这个情况一 ...

  3. nginx + SSL优化配置

    nginx + SSL优化配置: #http段添加如下配置项: http { ssl_prefer_server_ciphers on; #设置协商加密算法时,优先使用我们服务端的加密套件,而不是客户 ...

  4. 关于C中内存操作

     from:http://blog.csdn.net/shuaishuai80/article/details/6140979 malloc.calloc.realloc的区别 C Language ...

  5. 2017《时间的朋友》罗振宇跨年演讲ppt

    2016年12月31日晚,罗辑思维的罗振宇将在深圳湾春茧体育馆进行2017<时间的朋友>跨年演讲,很多网友一直在找直播的地址还是没找到,现在ytkah就第一时间分享一些精彩ppt弥补网友的 ...

  6. PHP中::、-&gt;、self、$this操作符的区别

    在访问PHP类中的成员变量或方法时,如果被引用的变量或者方法被声明成const(定义常量)或者static(声明静态),那么就必须使用操作符::,反之如果被引用的变量或者方法没有被声明成const或者 ...

  7. Array的个人总结

    <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" ...

  8. 优先队列实现Huffman编码

    首先把所有的字符加入到优先队列,然后每次弹出两个结点,用这两个结点作为左右孩子,构造一个子树,子树的跟结点的权值为左右孩子的权值的和,然后将子树插入到优先队列,重复这个步骤,直到优先队列中只有一个结点 ...

  9. 分页查询和分页缓存查询,List<Map<String, Object>>遍历和Map遍历

    分页查询 String sql = "返回所有符合条件记录的待分页SQL语句"; int start = (page - 1) * limit + 1; int end = pag ...

  10. Android控制ScrollView滚动

    有两种办法,第一种,使用scrollTo(),这个方法不需要handler,直接调用就行 第二种方式,使用fullScrol() 下面我们看一下这个函数: scrollView.fullScroll( ...