因为微软的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的更多相关文章

  1. NPOI导入导出EXCEL通用类,供参考,可直接使用在WinForm项目中

    以下是NPOI导入导出EXCEL通用类,是在别人的代码上进行优化的,兼容xls与xlsx文件格式,供参考,可直接使用在WinForm项目中,由于XSSFWorkbook类型的Write方法限制,Wri ...

  2. NPOI导入导出Excel

    .net mvc利用NPOI导入导出excel 注意:如何导出的提交方式ajax导出是失效的! 解决方案是:js处理l两个表单的提交  代码:  第一步. 在页面里面加入2个隐藏的iframe, 如下 ...

  3. .Net core NPOI导入导出Excel

    最近在想.net core NPOI 导入导出Excel,一开始感觉挺简单的,后来真的遇到很多坑.所以还是写一篇博客让其他人少走一些弯路,也方便忘记了再重温一遍.好了,多的不说,直接开始吧. 在.Ne ...

  4. Npoi导入导出Excel操作

    之前公司的一个物流商系统需要实现对订单的批量导入和导出,翻阅了一些资料,最后考虑使用NPOI实现这个需求. 在winform上面实现excel操作:http://www.cnblogs.com/Cal ...

  5. Excel操作--使用NPOI导入导出Excel为DataTable

    1.ExcelHelper封装 namespace NPOI操作Excel { public class ExcelHelper { /// <summary> /// DataTable ...

  6. NPOI导入导出EXCEL通用类,可直接使用在WinForm项目中

    由于XSSFWorkbook类型的Write方法限制,Write完成后就自动关闭流数据,所以无法很好的支持的Web模式,网上目前也未找到好的解决方案. 注意:若直接使用在WinForm项目中,必需先下 ...

  7. .net mvc利用NPOI导入导出excel

    1.导出Excel :首先引用NPOI包(Action一定要用FileResult) /// <summary> /// 批量导出需要导出的列表 /// </summary> ...

  8. ASP.Net MVC利用NPOI导入导出Excel

    因近期项目遇到所以记录一下: 首先导出Excel: 首先引用NPOI包 http://pan.baidu.com/s/1i3Fosux (Action一定要用FileResult) /// <s ...

  9. 使用NPOI导入导出Excel(xls/xlsx)数据到DataTable中

    using System; using System.Collections.Generic; using System.Text; using System.IO; using NPOI.SS.Us ...

随机推荐

  1. js创建命名空间

    CreateNameSpace: function () { var nameSpaceObjec = arguments[0].split('.'); var currentNameSpaceNam ...

  2. TS流格式(转)

    一 从TS流开始 数字电视机顶盒接收到的是一段段的码流,我们称之为TS(Transport Stream,传输流),每个TS流都携带一些信息,如Video.Audio以及我们需要学习的PAT.PMT等 ...

  3. 转载:MATLAB画图常用调整代码

    %单y轴 plot(t*1e+,abs(iGG)/max(abs(iGG)),); axis([-,,,]) xlabel('时间/ns'); ylabel('幅度/a.u.'); ,'FontNam ...

  4. C#防SQL注入代码的实现方法

    对于网站的安全性,是每个网站开发者和运营者最关心的问题.网站一旦出现漏洞,那势必将造成很大的损失.为了提高网站的安全性,首先网站要防注入,最重要的是服务器的安全设施要做到位. 下面说下网站防注入的几点 ...

  5. junit 基础使用

    junit百度百科: JUnit是一个Java语言的单元测试框架.它由Kent Beck和Erich Gamma建立,逐渐成为源于Kent Beck的sUnit的xUnit家族中最为成功的一个. JU ...

  6. ZooKeeper 典型的应用场景——及编程实现

    如何使用 Zookeeper 作为一个分布式的服务框架,主要用来解决分布式集群中应用系统的一致性问题,它能提供基于类似于文件系统的目录节点树方式的数据存储,但是 Zookeeper 并不是用来专门存储 ...

  7. Numpy 通用函数

    frompyfunc的调用格式为frompyfunc(func, nin, nout),其中func是计算单个元素的函数,nin是此函数的输入参数的个数,nout是此函数的返回值的个数 # 注:用fr ...

  8. html代码段

    添加icon<link rel="shortcut icon" href="img/100du.ico"/>

  9. json ubuntu下安装

    1.首先安装scons scons是linux下的自动构建工具,类似cmake. 下载地址wget http://prdownloads.sourceforge.net/scons/scons-2.2 ...

  10. 20155333 《网络对抗》 Exp8 Web基础

    20155333 <网络对抗> Exp8 Web基础 基础问题 (1)什么是表单? 表单在网页中主要负责数据采集功能. 一个表单有三个基本组成部分: 表单标签,这里面包含了处理表单数据所用 ...