NPOI 导入导出excel 支持 03 07
因为微软的office成本太高了,所以开发项目的时候电脑上没安装office,而是安装了wps。但开发语言用的是C#,所以直接调用微软的office组件是很方便的,但一方面慢,一方面成本高,所以从网上找到了NPOI这个开源的项目。http://npoi.codeplex.com/,引用的dll下载目录 http://npoi.codeplex.com/downloads/get/1476595
并且封装了通用的处理EXCEL 跟DataSet,DataTable的方法。方便调用
以上是代码 (当前项目是.net 2.0 下的,如果需要.net 4.0则到NPOI官网下载相应的dll就可以了)
using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text; namespace MrLiu.Tools
{
public sealed class ExcelHelper
{
#region Excel导入
/// <summary>
/// Excel 转换为DataTable
/// </summary>
/// <param name="file">文件路径</param>
/// <param name="sheetName">Sheet名称,如果只有一个sheet可以传 null</param>
/// <returns></returns>
public static DataTable ExcelToDataTable(string file, string sheetName)
{
try
{
DataTable dt = new DataTable();
using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read))
{
var workbook = NPOI.SS.UserModel.WorkbookFactory.Create(fs);
ISheet sheet = null;
if (sheetName == null)
{
sheet = workbook.GetSheetAt();
}
else
{
sheet = workbook.GetSheet(sheetName);
}
//列名
IRow rowHead = sheet.GetRow(sheet.FirstRowNum);
for (int i = ; i < rowHead.LastCellNum; i++)
{
string fildName = rowHead.GetCell(i).StringCellValue;
dt.Columns.Add(fildName, typeof(String));
} //数据
for (int i = sheet.FirstRowNum + ; i <= sheet.LastRowNum; i++)
{
IRow row = sheet.GetRow(i);
DataRow dr = dt.NewRow();
for (int j = row.FirstCellNum; j < row.LastCellNum; j++)
{
var cell = row.GetCell(j);
dr[j] = GetValueTypeForICell(cell);
if (dr[j] == null)
{
dr[j] = string.Empty;
}
}
dt.Rows.Add(dr);
}
}
return dt;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
/// <summary>
/// Excel 导入为DataTable
/// </summary>
/// <param name="file">文件路径</param>
/// <param name="extension">后续名 XLS XLSX</param>
/// <returns></returns>
public static DataTable ExcelToDataTable(string file)
{
try
{
DataTable dt = new DataTable();
string extension = Path.GetExtension(file);
if (extension.ToUpper() == ".XLS")
{
dt = ExcelToTableForXLS(file);
}
else if (extension.ToUpper() == ".XLS")
{
dt = ExcelToTableForXLSX(file);
}
else
{
throw new Exception("文件格式不正确");
}
return dt;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
/// <summary>
/// 读取xls格式的Excel
/// </summary>
/// <param name="file">文件全路径</param>
/// <returns>返回DaTaTable</returns>
public static DataTable ExcelToTableForXLS(string file)
{
try
{
DataTable dt = new DataTable();
using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read))
{
var hssfworkbook = new NPOI.HSSF.UserModel.HSSFWorkbook(fs);
ISheet sheet = hssfworkbook.GetSheetAt(); //列名
IRow rowHead = sheet.GetRow(sheet.FirstRowNum);
for (int i = ; i < rowHead.LastCellNum; i++)
{
string fildName = rowHead.GetCell(i).StringCellValue;
dt.Columns.Add(fildName, typeof(String));
} //数据
for (int i = sheet.FirstRowNum + ; i <= sheet.LastRowNum; i++)
{
IRow row = sheet.GetRow(i);
DataRow dr = dt.NewRow();
for (int j = row.FirstCellNum; j < row.LastCellNum; j++)
{
NPOI.HSSF.UserModel.HSSFCell cell = row.GetCell(j) as NPOI.HSSF.UserModel.HSSFCell;
dr[j] = GetValueTypeForXLS(cell);
if (dr[j] == null)
{
break;
}
}
dt.Rows.Add(dr);
}
}
return dt;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
} /// <summary>
/// 获取单元格类型
/// </summary>
/// <param name="cell"></param>
/// <returns></returns>
private static object GetValueTypeForXLS(NPOI.HSSF.UserModel.HSSFCell cell)
{
try
{
if (cell == null)
{
return null;
}
switch (cell.CellType)
{
case CellType.Blank: //BLANK:
return null;
case CellType.Boolean: //BOOLEAN:
return cell.BooleanCellValue;
case CellType.Numeric: //NUMERIC:
return cell.NumericCellValue;
case CellType.String: //STRING:
return cell.StringCellValue;
case CellType.Error: //ERROR:
return cell.ErrorCellValue;
case CellType.Formula: //FORMULA:
default:
return "=" + cell.CellFormula;
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
} /// <summary>
/// 读取xlsx格式的Excel
/// </summary>
/// <param name="file">文件全路径</param>
/// <returns>返回DaTaTable</returns>
public static DataTable ExcelToTableForXLSX(string file)
{
try
{
DataTable dt = new DataTable();
using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read))
{
var hssfworkbook = new NPOI.XSSF.UserModel.XSSFWorkbook(fs);
ISheet sheet = hssfworkbook.GetSheetAt(); //列名
IRow rowHead = sheet.GetRow(sheet.FirstRowNum);
for (int i = ; i < rowHead.LastCellNum; i++)
{
string fildName = rowHead.GetCell(i).StringCellValue;
dt.Columns.Add(fildName, typeof(String));
} //数据
for (int i = sheet.FirstRowNum + ; i <= sheet.LastRowNum; i++)
{
IRow row = sheet.GetRow(i);
DataRow dr = dt.NewRow();
for (int j = row.FirstCellNum; j < row.LastCellNum; j++)
{
NPOI.HSSF.UserModel.HSSFCell cell = row.GetCell(j) as NPOI.HSSF.UserModel.HSSFCell;
dr[j] = GetValueTypeForXLS(cell);
if (dr[j] == null)
{
break;
}
}
dt.Rows.Add(dr);
}
}
return dt;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
/// <summary>
/// 获取单元格类型(xlsx)
/// </summary>
/// <param name="cell"></param>
/// <returns></returns>
private static object GetValueTypeForXLSX(NPOI.XSSF.UserModel.XSSFCell cell)
{
try
{
if (cell == null)
{
return null;
}
switch (cell.CellType)
{
case CellType.Blank: //BLANK:
return null;
case CellType.Boolean: //BOOLEAN:
return cell.BooleanCellValue;
case CellType.Numeric: //NUMERIC:
return cell.NumericCellValue;
case CellType.String: //STRING:
return cell.StringCellValue;
case CellType.Error: //ERROR:
return cell.ErrorCellValue;
case CellType.Formula: //FORMULA:
default:
return "=" + cell.CellFormula;
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
} /// <summary>
/// 获取单元格类型不定
/// </summary>
/// <param name="cell"></param>
/// <returns></returns>
private static object GetValueTypeForICell(ICell cell)
{
try
{
if (cell == null)
{
return null;
}
switch (cell.CellType)
{
case CellType.Blank: //BLANK:
return null;
case CellType.Boolean: //BOOLEAN:
return cell.BooleanCellValue;
case CellType.Numeric: //NUMERIC:
return cell.NumericCellValue;
case CellType.String: //STRING:
return cell.StringCellValue;
case CellType.Error: //ERROR:
return cell.ErrorCellValue;
case CellType.Formula: //FORMULA:
default:
return "=" + cell.CellFormula;
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
} /// <summary>
/// Excel 转换为DataSet
/// </summary>
/// <param name="fileName">文件名</param>
/// <returns>DataSet</returns>
public static DataSet ExcelToDataSet(string fileName)
{
try
{
if (!File.Exists(fileName))
{
throw new Exception("文件不存在");
}
else
{
DataSet ds = new DataSet();
using (FileStream reader = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
{
IWorkbook book = WorkbookFactory.Create(reader);
int cnt = book.NumberOfSheets;
if (cnt <= )
{
throw new Exception("文件不是Excel文件");
} for (int i = ; i < cnt; i++)
{
ISheet sheet = book.GetSheetAt(i);
DataTable dt = new DataTable(sheet.SheetName);
IRow rowHead = sheet.GetRow(sheet.FirstRowNum);
for (int j = rowHead.FirstCellNum; j < rowHead.LastCellNum; j++)
{
ICell cell = rowHead.GetCell(j);
dt.Columns.Add(cell.StringCellValue);
}
for (int j = sheet.FirstRowNum + ; j <= sheet.LastRowNum; j++)
{
DataRow dr = dt.NewRow();
IRow row = sheet.GetRow(j);
for (int k = rowHead.FirstCellNum; k < rowHead.LastCellNum; k++)
{
dr[k] = row.GetCell(k).StringCellValue;
}
dt.Rows.Add(dr);
}
ds.Tables.Add(dt);
}
}
return ds;
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
#endregion Excel导出 #region Excel导出 /// <summary>
/// Excel导出
/// </summary>
/// <param name="dt">虚拟表</param>
/// <param name="fileName">文件路径</param>
/// <param name="sheetName">Sheet路径为空请传null</param>
/// <returns></returns>
public static bool DataTableToXLS(DataTable dt, string fileName, string sheetName)
{
try
{
if (dt == null)
{
return false;
}
if (String.IsNullOrEmpty(sheetName))
{
sheetName = Path.GetFileName(fileName);
}
var book = new NPOI.HSSF.UserModel.HSSFWorkbook();
book.CreateSheet();
var sheet = book.CreateSheet(sheetName); IRow rowHead = sheet.CreateRow();
for (int i = ; i < dt.Columns.Count; i++)
{
ICell cell = rowHead.CreateCell(i);
cell.SetCellValue(dt.Columns[i].ColumnName);
}
for (int i = ; i < dt.Rows.Count; i++)
{
IRow row = sheet.CreateRow(i + );
for (int j = ; j < dt.Columns.Count; j++)
{
ICell cell = row.CreateCell(j);
cell.SetCellValue(dt.Rows[i][j].ToString());
}
} using (FileStream fsWriter = new FileStream(fileName, FileMode.Append, FileAccess.Write, FileShare.Write))
{
book.Write(fsWriter);
return true;
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
} /// <summary>
/// DataSet 导出 到Excel
/// </summary>
/// <param name="ds">DataSet 表名默认为sheet名</param>
/// <param name="fileName">文件路径</param>
public static bool DataSetToExcel(DataSet ds, string fileName)
{
try
{
String extension = Path.GetExtension(fileName).ToUpper();
IWorkbook book = null;
if (extension == ".XLS")
{
book = DataSetToHSSFWordbook(ds);
}
else if (extension == ".XLSX")
{
book = DataSetToXSSFWorkbook(ds);
}
else
{
throw new Exception("导入格式必须为xls或者xlsx");
} using (FileStream fsWriter = new FileStream(fileName, FileMode.CreateNew, FileAccess.Write, FileShare.ReadWrite))
{
book.Write(fsWriter);
return true;
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
/// <summary>
/// DataSet 转换为 XSSFWorkbook 07
/// </summary>
/// <param name="ds"></param>
/// <returns></returns>
private static NPOI.XSSF.UserModel.XSSFWorkbook DataSetToXSSFWorkbook(DataSet ds)
{
try
{
var book = new NPOI.XSSF.UserModel.XSSFWorkbook();
foreach (DataTable dt in ds.Tables)
{
ISheet sheet = book.CreateSheet(dt.TableName);
IRow rowHead = sheet.CreateRow();
ICellStyle style = book.CreateCellStyle();
style.BorderBottom = BorderStyle.Thin;
style.BorderTop = BorderStyle.Thin;
style.BorderLeft = BorderStyle.Thin;
style.BorderRight = BorderStyle.Thin;
IFont font = book.CreateFont();
font.FontHeightInPoints = ;
font.IsBold = true;
style.SetFont(font);
for (int i = ; i < dt.Columns.Count; i++)
{
ICell cell = rowHead.CreateCell(i);
cell.CellStyle = style;
cell.SetCellValue(dt.Columns[i].ColumnName);
}
font.IsBold = false;
style.SetFont(font);
for (int i = ; i < dt.Rows.Count; i++)
{
IRow row = sheet.CreateRow(i + );
DataRow dr = dt.Rows[i];
for (int j = ; j < dt.Columns.Count; j++)
{
ICell cell = row.CreateCell(j);
cell.CellStyle = style;
cell.SetCellValue(dr[j].ToString());
}
}
}
return book;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
} /// <summary>
/// DataSet 转换为 HSSFWorkbook 03
/// </summary>
/// <param name="ds"></param>
/// <returns></returns>
private static NPOI.HSSF.UserModel.HSSFWorkbook DataSetToHSSFWordbook(DataSet ds)
{
try
{
var book = new NPOI.HSSF.UserModel.HSSFWorkbook();
var dsi = NPOI.HPSF.PropertySetFactory.CreateDocumentSummaryInformation();
dsi.Company = "xx软件股份有限公司";
var si = NPOI.HPSF.PropertySetFactory.CreateSummaryInformation();
si.Subject = "xx系统自动导出";
book.DocumentSummaryInformation = dsi;
book.SummaryInformation = si; foreach (DataTable dt in ds.Tables)
{
ISheet sheet = book.CreateSheet(dt.TableName);
IRow rowHead = sheet.CreateRow();
ICellStyle style = book.CreateCellStyle();
style.BorderBottom = BorderStyle.Thin;
style.BorderTop = BorderStyle.Thin;
style.BorderLeft = BorderStyle.Thin;
style.BorderRight = BorderStyle.Thin;
IFont font = book.CreateFont();
font.FontHeightInPoints = ;
font.IsBold = true;
style.SetFont(font);
for (int i = ; i < dt.Columns.Count; i++)
{
ICell cell = rowHead.CreateCell(i);
cell.CellStyle = style;
cell.SetCellValue(dt.Columns[i].ColumnName);
}
font.IsBold = false;
style.SetFont(font);
for (int i = ; i < dt.Rows.Count; i++)
{
IRow row = sheet.CreateRow(i + );
DataRow dr = dt.Rows[i];
for (int j = ; j < dt.Columns.Count; j++)
{
ICell cell = row.CreateCell(j);
cell.CellStyle = style;
cell.SetCellValue(dr[j].ToString());
}
}
}
return book;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
} #endregion
}
}
NPOI 导入导出excel 支持 03 07的更多相关文章
- NPOI导入导出EXCEL通用类,供参考,可直接使用在WinForm项目中
以下是NPOI导入导出EXCEL通用类,是在别人的代码上进行优化的,兼容xls与xlsx文件格式,供参考,可直接使用在WinForm项目中,由于XSSFWorkbook类型的Write方法限制,Wri ...
- NPOI导入导出Excel
.net mvc利用NPOI导入导出excel 注意:如何导出的提交方式ajax导出是失效的! 解决方案是:js处理l两个表单的提交 代码: 第一步. 在页面里面加入2个隐藏的iframe, 如下 ...
- .Net core NPOI导入导出Excel
最近在想.net core NPOI 导入导出Excel,一开始感觉挺简单的,后来真的遇到很多坑.所以还是写一篇博客让其他人少走一些弯路,也方便忘记了再重温一遍.好了,多的不说,直接开始吧. 在.Ne ...
- Npoi导入导出Excel操作
之前公司的一个物流商系统需要实现对订单的批量导入和导出,翻阅了一些资料,最后考虑使用NPOI实现这个需求. 在winform上面实现excel操作:http://www.cnblogs.com/Cal ...
- Excel操作--使用NPOI导入导出Excel为DataTable
1.ExcelHelper封装 namespace NPOI操作Excel { public class ExcelHelper { /// <summary> /// DataTable ...
- NPOI导入导出EXCEL通用类,可直接使用在WinForm项目中
由于XSSFWorkbook类型的Write方法限制,Write完成后就自动关闭流数据,所以无法很好的支持的Web模式,网上目前也未找到好的解决方案. 注意:若直接使用在WinForm项目中,必需先下 ...
- .net mvc利用NPOI导入导出excel
1.导出Excel :首先引用NPOI包(Action一定要用FileResult) /// <summary> /// 批量导出需要导出的列表 /// </summary> ...
- ASP.Net MVC利用NPOI导入导出Excel
因近期项目遇到所以记录一下: 首先导出Excel: 首先引用NPOI包 http://pan.baidu.com/s/1i3Fosux (Action一定要用FileResult) /// <s ...
- 使用NPOI导入导出Excel(xls/xlsx)数据到DataTable中
using System; using System.Collections.Generic; using System.Text; using System.IO; using NPOI.SS.Us ...
随机推荐
- matlab clear
clear 删除工作空间中的项目,释放系统内存 语法: clear clear name clear name1 name2 name3... clear global name clear -reg ...
- <读书笔记>软件调试之道 :问题的核心-重现问题
声明:本文档的内容主要来源于书籍<软件调试修炼之道>作者Paul Butcher,属于读书笔记. 重现第一,提问第二 问题重现是实证过程的最强大武器,如果不能重现问题,你也无法证明修复了它 ...
- 修改tomcat应用日志默认编码格式
前言 今天开发跟我说tomcat日志中的中文不能正常显示,根据以往的经验,我觉得可能跟服务器的编码有关,于是尝试各种方法,但还是没能解决问题. 后来我突然想到会不会跟tomcat的设置有关呢,于是在网 ...
- AIX 环境下遇到Device Busy问题
IBM AIX v5.3操作系统环境下在对网络或网卡进行操作过程中经常遇到"Device Busy"而终止操作例如:#rmdev -l ent1遇到如下返回信息Method err ...
- GPL 和BSD和Apache
开源许可证GPL.BSD.MIT.Mozilla.Apache和LGPL的区别<ignore_js_op> 以下是上述协议的简单介绍:BSD开源协议BSD开源协议是一个给于使用者很大自由的 ...
- iOS强制屏幕旋转
/** 强制旋转屏幕为纵向 (注:这种方式 键盘不能旋转过来; iOS8.x下 UIAlterView旋转不过来 ) @return */ + (void)rotateOrientationPort ...
- 锋利的js前端分页之jQuery
大家在作分页时,多数是在后台返回一个导航条的html字符串,其实在前端用js也很好实现. 调用pager方法,输入参数,会返回一个导航条的html字符串.方法的内部比较简单. /** * pageSi ...
- SQL Server(三):Select语句
1.最基本的Select语句: Select [Top n [With Ties]] <*|Column_Name [As <Alias>][, ...n]> From & ...
- kendo ui 富文本编辑控件 Editor 实现本地上传图片,并显示
富文本编辑的组件有很多,大名鼎鼎的KENDO UI中自然也有,但是默认功能中,只能包含网络图片, 而如果要实现本地上传图片,KENDO UI也提供了相应的功能,但必须实现KENDO规定的多个接口, 而 ...
- redis命令String
$ keys * $ rename oldkey newkey $ renamex oldkey newkey 新key存在抛出异常 $ dbsize $ expire key 时间(秒) $ ttl ...