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 ...
随机推荐
- jenkins:通过execute shell启动的进程会被杀死的问题
[问题]在jenkins中配置自动更新部署项目时,如果采取用execute shell启动/关闭tomcat,会发现可以进行关闭tomcat,但是无法启动tomcat,虽然构建会显示执行成功,但是查看 ...
- leetcode 205
205. Isomorphic Strings Given two strings s and t, determine if they are isomorphic. Two strings are ...
- python学习:环境搭建
1.图解eclipse环境下安装python3.x插件支持:http://www.tuicool.com/articles/M3Afyu 其中如果 然后,选择Add按钮,Name:Python3,Lo ...
- Js获取图片原始宽高
如果我们页面看到的图片都是缩略图,那就需要做个图片点击放大效果,那么怎样获取图片的原始宽高呢?方法如下: //获取图片原始宽度 function getNaturalWidthAndHeight(im ...
- C--关键字static
static在C中主要有两个作用: 1.修饰变量 (局部变量.全局变量 都存在内存的静态区) 静态全局变量: 作用域仅限于变量被定义的文件中,其中文件即使用extern声明也无法使用它. 静态局部变 ...
- HTML。CSS浮动元素详解
浮动定位是指 1.1将元素排除在普通流之外,即元素将脱离标准文档流 1.2元素将不在页面占用空间 1.3将浮动元素放置在包含框的左边或者右边 1.4浮动元素依旧位于包含框之内 2. 浮动的框可以向左或 ...
- 自己实现多线程的socket,socketserver源码剖析
1,IO多路复用 三种多路复用的机制:select.poll.epoll 用的多的两个:select和epoll 简单的说就是:1,select和poll所有平台都支持,epoll只有linux支持2 ...
- 运行R 报错R cannot R_TempDir, 继而发现/dev/mapper/VG00-LV01 磁盘空间已满
今天在运行R脚本的时候报了个错:Fatal error: cannot create 'R_TempDir'.排除了是自己写的代码的问题,想着应该是某个没见过的原因,google之,发现网上的说法是/ ...
- div水平居中且垂直居中
<style> .vertical-center{ position: absolute; top: 50%; left: 50%; transform: translate(-50%, ...
- MySQL效能监控工具mysqlreport安装和中文说明
管理 mysql 最让人困扰的就是如何有效的掌握 MySQL 的健康状况,因为 MySQL 虽然有提供许多系统变量值供您参考,但这些零散的数据若要手动搜集与过滤将会是一件十分没有效率的事情(除非您写 ...