使用 EPPlus,NPOI,操作EXCEL
NPOI, 读取xls文件(Excel2003及之前的版本) (NPOI.dll+Ionic.Zip.dll) http://npoi.codeplex.com/
EPPlus, 读取xlsx文件(Excel2007版本) (EPPlus.dll) http://epplus.codeplex.com/
本文中只实现了Excel文件的读取,实际上,这两个控件均支持对其内容,格式,公式等进行修改,这些复杂功能尚无需求,所以没有实现
读取接口IExcel:


Codepublic interface IExcel
{
/// <summary> 打开文件 </summary>
bool Open();
/// <summary> 文件版本 </summary>
ExcelVersion Version { get; }
/// <summary> 文件路径 </summary>
string FilePath { get; set; }
/// <summary> 文件是否已经打开 </summary>
bool IfOpen { get; }
/// <summary> 文件包含工作表的数量 </summary>
int SheetCount { get; }
/// <summary> 当前工作表序号 </summary>
int CurrentSheetIndex { get; set; }
/// <summary> 获取当前工作表中行数 </summary>
int GetRowCount();
/// <summary> 获取当前工作表中列数 </summary>
int GetColumnCount();
/// <summary> 获取当前工作表中某一行中单元格的数量 </summary>
/// <param name="Row">行序号</param>
int GetCellCountInRow(int Row);
/// <summary> 获取当前工作表中某一单元格的值(按字符串返回) </summary>
/// <param name="Row">行序号</param>
/// <param name="Col">列序号</param>
string GetCellValue(int Row, int Col);
/// <summary> 关闭文件 </summary>
void Close();
} public enum ExcelVersion
{
/// <summary> Excel2003之前版本 ,xls </summary>
Excel03,
/// <summary> Excel2007版本 ,xlsx </summary>
Excel07
xls文件实现:


Codeusing NPOI.HSSF.UserModel; public class Excel03:IExcel
{
public Excel03()
{ } public Excel03(string path)
{ filePath = path; } private FileStream file = null;
private string filePath = "";
private HSSFWorkbook book = null;
private int sheetCount=0;
private bool ifOpen = false;
private int currentSheetIndex = 0;
private HSSFSheet currentSheet = null; public string FilePath
{
get { return filePath; }
set { filePath = value; }
} public bool Open()
{
try
{
file = new FileStream(filePath, FileMode.Open, FileAccess.Read);
book= new HSSFWorkbook(file); if (book == null) return false;
sheetCount = book.NumberOfSheets;
currentSheetIndex = 0;
currentSheet = (HSSFSheet)book.GetSheetAt(0);
ifOpen = true;
}
catch (Exception ex)
{
throw new Exception("打开文件失败,详细信息:" + ex.Message);
}
return true;
} public void Close()
{
if (!ifOpen) return;
file.Close();
} public ExcelVersion Version
{ get { return ExcelVersion.Excel03; } } public bool IfOpen
{ get { return ifOpen; } } public int SheetCount
{ get { return sheetCount; } } public int CurrentSheetIndex
{
get { return currentSheetIndex; }
set
{
if (value != currentSheetIndex)
{
if (value >= sheetCount)
throw new Exception("工作表序号超出范围");
currentSheetIndex = value;
currentSheet = (HSSFSheet)book.GetSheetAt(currentSheetIndex);
}
}
} public int GetRowCount()
{
if (currentSheet == null) return 0;
return currentSheet.LastRowNum + 1;
} public int GetColumnCount()
{
if (currentSheet == null) return 0;
int colCount = 0;
for (int i = 0; i <= currentSheet.LastRowNum; i++)
{
if (currentSheet.GetRow(i) != null && currentSheet.GetRow(i).LastCellNum+1 > colCount)
colCount = currentSheet.GetRow(i).LastCellNum + 1;
}
return colCount;
} public int GetCellCountInRow(int Row)
{
if (currentSheet == null) return 0;
if (Row > currentSheet.LastRowNum) return 0;
if (currentSheet.GetRow(Row) == null) return 0; return currentSheet.GetRow(Row).LastCellNum+1;
} public string GetCellValue(int Row, int Col)
{
if (Row > currentSheet.LastRowNum) return "";
if (currentSheet.GetRow(Row) == null) return "";
HSSFRow r = (HSSFRow)currentSheet.GetRow(Row); if (Col > r.LastCellNum) return "";
if (r.GetCell(Col) == null) return "";
return r.GetCell(Col).StringCellValue;
}
xlsx文件实现:


Codeusing OfficeOpenXml; public class Excel07:IExcel
{
public Excel07()
{ } public Excel07(string path)
{ filePath = path; } private string filePath = "";
private ExcelWorkbook book = null;
private int sheetCount = 0;
private bool ifOpen = false;
private int currentSheetIndex = 0;
private ExcelWorksheet currentSheet = null;
private ExcelPackage ep = null; public bool Open()
{
try
{
ep = new ExcelPackage(new FileInfo(filePath)); if (ep == null) return false;
book =ep.Workbook;
sheetCount = book.Worksheets.Count;
currentSheetIndex = 0;
currentSheet = book.Worksheets[1];
ifOpen = true;
}
catch (Exception ex)
{
throw new Exception("打开文件失败,详细信息:" + ex.Message);
}
return true;
} public void Close()
{
if (!ifOpen || ep == null) return;
ep.Dispose();
} public ExcelVersion Version
{ get { return ExcelVersion.Excel07; } } public string FilePath
{
get { return filePath; }
set { filePath = value; }
} public bool IfOpen
{ get { return ifOpen; } } public int SheetCount
{ get { return sheetCount; } } public int CurrentSheetIndex
{
get { return currentSheetIndex; }
set
{
if (value != currentSheetIndex)
{
if (value >= sheetCount)
throw new Exception("工作表序号超出范围");
currentSheetIndex = value;
currentSheet =book.Worksheets[currentSheetIndex+1];
}
}
} public int GetRowCount()
{
if (currentSheet == null) return 0;
return currentSheet.Dimension.End.Row;
} public int GetColumnCount()
{
if (currentSheet == null) return 0;
return currentSheet.Dimension.End.Column;
} public int GetCellCountInRow(int Row)
{
if (currentSheet == null) return 0;
if (Row >= currentSheet.Dimension.End.Row) return 0;
return currentSheet.Dimension.End.Column;
} public string GetCellValue(int Row, int Col)
{
if (currentSheet == null) return "";
if (Row >= currentSheet.Dimension.End.Row || Col >= currentSheet.Dimension.End.Column) return "";
object tmpO =currentSheet.GetValue(Row + 1, Col + 1);
if (tmpO == null) return "";
return tmpO.ToString();
}
调用类:


Codepublic class ExcelLib
{
/// <summary> 获取Excel对象 </summary>
/// <param name="filePath">Excel文件路径</param>
/// <returns></returns>
public static IExcel GetExcel(string filePath)
{
if (filePath.Trim() == "")
throw new Exception("文件名不能为空"); if(!filePath.Trim().EndsWith("xls") && !filePath.Trim().EndsWith("xlsx"))
throw new Exception("不支持该文件类型"); if (filePath.Trim().EndsWith("xls"))
{
IExcel res = new Excel03(filePath.Trim());
return res;
}
else if (filePath.Trim().EndsWith("xlsx"))
{
IExcel res = new Excel07(filePath.Trim());
return res;
}
else return null;
}
调用:
ExcelLib.IExcel tmp = ExcelLib.ExcelLib.GetExcel(Application.StartupPath + "\\TestUnicodeChars.xls");
//ExcelLib.IExcel tmp = ExcelLib.ExcelLib.GetExcel(Application.StartupPath + "\\TestUnicodeChars.xlsx");
if (tmp == null) MessageBox.Show("打开文件错误");
try
{
if (!tmp.Open())
MessageBox.Show("打开文件错误");
tmp.CurrentSheetIndex = 1;
int asdf = tmp.GetColumnCount();
string sdf = tmp.GetCellValue(0,1);
tmp.Close();
}
catch (Exception ex)
{ MessageBox.Show(ex.Message); return
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Fix Asset");
//Load the datatable into the sheet, starting from cell A1. Print the column names on row 1
//ws.Cells["A1"].LoadFromDataTable(tbl, true);
ws.Cells["A1"].LoadFromCollection(assets, true);//collection型数据源
//写到客户端(下载)
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=FixAsset.xlsx");
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.BinaryWrite(pck.GetAsByteArray());
//ep.SaveAs(Response.OutputStream); 第二种方式
Response.Flush();
Response.End();
注意:如果是在ASCX中调用,需要:
在Page_Load中注册两行Javascript脚本,string script = “_spOriginalFormAction = document.forms[0].action;\n_spSuppressFormOnSubmitWrapper = true;”;
this.ClientScript.RegisterClientScriptBlock(this.GetType(), “script”, script, true);
可以查看:http://www.cnblogs.com/ceci/archive/2012/09/05/2671538.html
使用 EPPlus,NPOI,操作EXCEL的更多相关文章
- NPOI操作Excel辅助类
/// <summary> /// NPOI操作excel辅助类 /// </summary> public static class NPOIHelper { #region ...
- NPOI操作excel之写入数据到excel表
在上一篇<NPOI操作excel之读取excel数据>我们把excel数据写入了datatable中,本篇就讲如何把datatable数据写入excel中. using System; u ...
- C#开发中使用Npoi操作excel实例代码
C#开发中使用Npoi操作excel实例代码 出处:西西整理 作者:西西 日期:2012/11/16 9:35:50 [大 中 小] 评论: 0 | 我要发表看法 Npoi 是什么? 1.整个Exce ...
- 用NPOI操作EXCEL关于HSSFClientAnchor(dx1,dy1,dx2,dy2,col1,row1,col2,row2)的参数
2.4.1 用NPOI操作EXCEL关于HSSFClientAnchor(dx1,dy1,dx2,dy2,col1,row1,col2,row2)的参数 NPOI教程:http://www.cnb ...
- C# 如何使用NPOI操作Excel以及读取合并单元格等
C#操作Excel方法有很多,以前用的需要电脑安装office才能用,但因为版权问题公司不允许安装office.所以改用NPOI进行Excel操作,基本上一些简单的Excel操作都没有问题,读写合并单 ...
- 用NPOI操作EXCEL-锁定列CreateFreezePane()
public void ExportPermissionRoleData(string search, int roleStatus) { var workbook = new HSSFWorkboo ...
- .NET 通过 NPOI 操作 Excel
目录 .NET 通过 NPOI 操作 Excel 第一步:通过 NuGet 获取 NPOI 包并引入程序集 第二步:引入 NPOI 帮助类 第三步:在程序中调用相应的方法对数据进行导出导入操作 将 D ...
- 2.6.2 用NPOI操作EXCEL--设置密码才可以修改单元格内容
2.6.2 用NPOI操作EXCEL--设置密码 有时,我们可能需要某些单元格只读,如在做模板时,模板中的数据是不能随意让别人改的.在Excel中,可以通过“审阅->保护工作表”来完 ...
- 使用NPOI操作Excel文件及其日期处理
工作中经常遇到需要读取或导出Excel文件的情况,而NPOI是目前最宜用.效率最高的操作的Office(不只是Excel哟)文件的组件,使用方便,不详细说明了. Excel工作表约定:整个Excel表 ...
- [Solution] NPOI操作Excel
NPOI 是 POI 项目的 .NET 版本.POI是一个开源的Java读写Excel.WORD等微软OLE2组件文档的项目.使用 NPOI 你就可以在没有安装 Office 或者相应环境的机器上对 ...
随机推荐
- UVa 11400 Lighting System Design
题意: 一共有n种灯泡,不同种类的灯泡必须用不同种电源,但同一种灯泡可以用同一种电源.每种灯泡有四个参数: 电压值V.电源费用K.每个灯泡的费用C.所需该种灯泡的数量L 为了省钱,可以用电压高的灯泡来 ...
- bzoj1834: [ZJOI2010]network 网络扩容
努力看了很久样例一直过不了...然后各种输出中间过程啊巴拉巴拉弄了1h,没办法了...然后突然想到啊原来的边可以用啊为什么不用...于是A了...感人肺腑 #include<cstdio> ...
- HDU 5313 Bipartite Graph (二分图着色,dp)
题意: Soda有一个n个点m条边的二分图, 他想要通过加边使得这张图变成一个边数最多的完全二分图. 于是他想要知道他最多能够新加多少条边. 注意重边是不允许的. 思路: 先将二分图着色,将每个连通分 ...
- phpDoc 注释案例说明
<?php /** * start page for webaccess * * PHP version 5 * * @category PHP * @package PSI_Web * @au ...
- Java与WCF交互(一):Java客户端调用WCF服务
最近开始了解WCF,写了个最简单的Helloworld,想通过java客户端实现通信.没想到以我的基础,居然花了整整两天(当然是工作以外的时间,呵呵),整个过程大费周折,特写下此文,以供有需要的朋友参 ...
- gtid
GTID的全称为 global transaction identifier,可以翻译为全局事务标示符,GTID在原始master上的事务提交时被创建.GTID需要在全局的主-备拓扑结构中保持唯一性, ...
- OpenGL开发时,fatal error C1083: 无法打开包括文件:“gl\glut.h”: No such file or directory
本人使用的是vs2012,编写一个简单的opengl程序,运行的时候总是提示: fatal error C1083: 无法打开包括文件:“gl/glut.h”: No such file or dir ...
- <转>数据库设计的三大范式
为了建立冗余较小.结构合理的数据库,设计数据库时必须遵循一定的规则.在关系型数据库中这种规则就称为范式.范式是符合某一种设计要求的总结.要想设计一个结构合理的关系型数据库,必须满足一定的范式. 在实际 ...
- C++ 使用Htmlcxx解析Html内容(VS编译库文件)
1.下载Htmlcxx,http://sourceforge.net/projects/htmlcxx/ 2.解压htmlcxx-0.85.tar.gz 3.打开htmlcxx.vcproj,注意是h ...
- 【windows核心编程】DLL相关(3)
DLL重定向 因为DLL的搜索路径有先后次序,假设有这样的场景:App1.exe使用MyDll1.0.dll, App2.exe使用MyDll2.0.dll, MyDll1.0 和 MyDll2.0是 ...