使用 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 或者相应环境的机器上对 ...
随机推荐
- 前端SPA框架一些看法
说起前端框架,我个人主张有框架不如无框架,这个观点要先从框架和库的区别说起. 我所理解的库,解决的是代码或是模块级别的复用或者对复杂度的封装问题;而框架,更多的是对模式级别的复用和对程序组织的规范,这 ...
- Uva 10881 Piotr’s Ants 蚂蚁
一根长度为 L 厘米的木棍上有 n 只蚂蚁,每只蚂蚁要么朝左爬,要么朝右爬,速度为 1 厘米/秒.当两只蚂蚁相撞时,二者同时调头(掉头用的时间忽略不计).给出每只蚂蚁的初始位置和朝向,计算 T 秒之后 ...
- Android平台下实现录音及播放录音功能的简介
录音及播放的方法如下: package com.example.audiorecord; import java.io.File; import java.io.IOException; import ...
- 【JS】<a>标签调用js中函数的几种方法
我们常用的在a标签中有点击事件: a href="javascript:js_method();" 这是我们平台上常用的方法,但是这种方法在传递this等参数的时候很容易出问题,而 ...
- 【转】第一次使用Android Studio时你应该知道的一切配置
原文网址:http://www.cnblogs.com/smyhvae/p/4390905.html [声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.c ...
- db file scattered read 等待事件
db file scattered read 等待事件: 我们经常会见到db file scattered read 等待事件,在生产环境中,这个等待事件可能更为常见.这个事件表明用户进程正在读数据 ...
- Android Thread.UncaughtExceptionHandler捕获
在Java 的异常处理机制中:如果抛出的是Exception异常的话,必须有try..catch..进行处理,属于checked exception.如果抛出的是RuntimeException异常的 ...
- shell小技巧
# awk '{a[$1]++;a[$2]++}END{for (i in a)print i "\t" a[i]}' list | grep -w 2 | awk '{print ...
- 解决:Unable to connect to repository https://dl-ssl.google.com/android/eclipse/site.xml
ailed to fectch URl https://dl-ssl.google.com/android/repository/addons_list.xml, reason: Connection ...
- 1045 整数礼物 c语言
描述 Na 给准备送给ZZ两个整数,a, b,他还计算了这两个整数的平均值c,碰巧c也是整数. 但是Na 突然把b给弄丢了,你要帮助Na通过a, c计算出来b的值. 输入 输入为一行,两个用空格隔开的 ...