基于NPOI导出和导入Excel
概述
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的更多相关文章
- 使用NPOI导出,读取EXCEL(可追加功能)
使用NPOI导出,读取EXCEL,具有可追加功能 看代码 using System; using System.Collections.Generic; using System.Text; usin ...
- NPOI导出数据到Excel
NPOI导出数据到Excel 前言 Asp.net操作Excel已经是老生长谈的事情了,可下面我说的这个NPOI操作Excel,应该是最好的方案了,没有之一,使用NPOI能够帮助开发者在没有安装微 ...
- 原生PHP网页导出和导入excel文件实例
原生PHP实现的网页导出和导入excel文件实例,包括上传也是用的原生.还可在exportExcel方法里设置字体等表格样式. 导出和导入表单代码: <p style="margin: ...
- ASP.NET基于NPOI导出数据
using System; using System.Collections; using System.Collections.Generic; using System.IO; using Sys ...
- C#导出和导入Excel模板功能
引用 Aspose.Cells; 基于WinForm 导入 private void btn_excel_input_Click(object sender, EventArgs e) { try ...
- SpringBoot基于easyexcel导出和写入Excel
easyexcel是阿里巴巴旗下开源项目,主要用于Excel文件的导入和导出处理,今天我们利用SpringBoot和easyexcel实战演示如何导出和写入Excel文件. 一.加入我们需要的ea ...
- JS导出、导入EXCEL(案例)
插件下载地址:http://oss.sheetjs.com/js-xlsx/xlsx.full.min.js 1.导出excel <!DOCTYPE html> <html> ...
- 基于NPOI导出Excel
在上一篇文章[关于大数据的查询与导出]中,提到了使用NPOI组件导出Excel,本想上次一起分享给大家,无奈最近比较忙,今天抽空整理了下,分享出来. 预置填充模板,并且需要支持公式计算; 可导入图片; ...
- 基于NPOI的Execl导入导出例子
源地址:http://bbs.csdn.net/topics/390830774
随机推荐
- IntelliJ IDEA mac 快捷键
cmd+O 查找类alt+cmd+O 符号shift+cmd+O 查找文件^+space 补全alt + F7 查找符号的使用情况F1 查看文档cmd+b 跳转定义,或者 鼠标+ctrlcmd+F12 ...
- leetcode 111 minimum depth of binary tree
problem description: Given a binary tree, find its minimum depth. The minimum depth is the number of ...
- 用R做逻辑回归之汽车贷款违约模型
数据说明 本数据是一份汽车贷款违约数据 application_id 申请者ID account_number 账户号 bad_ind 是否违约 vehicle_year ...
- 关于MySQL的wait_timeout连接超时问题报错解决方案
bug回顾 : 想必大家在用MySQL时都会遇到连接超时的问题,如下图所示: ### Cause: com.mysql.jdbc.exceptions.jdbc4.CommunicationsExce ...
- 遍历Map的方法
1.使用 entrySet() entrySet() --> 官方推荐将Map转换成Map.Entry对象的Set集合 Set entrys = map.entrySet(); Iterat ...
- JavaScript原型
prototype与_proto_ 对象的 prototype 属性的方法.属性为对象所属的那一"类"所共有.对象原型链通过 proto 属性向上寻找. 为 proto 指定 nu ...
- 现代软件工程作业 第二章 Github的使用
Github的使用 创建团队 Github首页点击Create Orginazation,出现如下界面: 填写相关信息,邀请团队成员: 点击确认,创建团队完成,界面如下: 创建新的版本库 点击Crea ...
- 关于unity如何制作mmo
昨天去看了下unity的成都openday,还是有很多收获的,之前我对于这类的活动始终提不起来兴趣,不过看来日后还是要多参加下类似的活动长长见识. 公司打算开发3d mmo手游,昨天好玩123恰好也分 ...
- [Hadoop] Hadoop学习历程 [持续更新中…]
1. Hadoop FS Shell Hadoop之所以可以实现分布式计算,主要的原因之一是因为其背后的分布式文件系统(HDFS).所以,对于Hadoop的文件操作需要有一套全新的shell指令来完成 ...
- [Algorithm] 群体智能优化算法之粒子群优化算法
同进化算法(见博客<[Evolutionary Algorithm] 进化算法简介>,进化算法是受生物进化机制启发而产生的一系列算法)和人工神经网络算法(Neural Networks,简 ...