使用 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 或者相应环境的机器上对 ...
随机推荐
- OK335xS dhcpcd porting
/********************************************************************** * OK335xS dhcpcd porting * 说 ...
- UVA 1663 Purifying Machine (二分图匹配,最大流)
题意: 给m个长度为n的模板串,模板串由0和1和*三种组成,且每串至多1个*,代表可0可1.模板串至多匹配2个串,即*号改成0和1,如果没有*号则只能匹配自己.问:模板串可以缩减为几个,同样可以匹配原 ...
- 【JSP】JSP动态显示时间
function showtime() { var today; var hour; var second; var minute; var year; var month; var date; va ...
- ECshop 二次开发模板教程1
本教程适用于了解 ECshop 和 ECshop模板DIY 以及它们的日常使用,在查看前阁下需要至少会使用一种编辑器(exp:Dreamweaver, editplus, emacs, vi, ee ...
- echo二次开发 ecshop 函数列表
lib_time.php (时间函数) gmtime() P: 获得当前格林威治时间的时间戳 /$0 server_timezone() P: 获得服务器的时区 /$0 local_mktime($h ...
- context.Response.End()的用法和本质
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Web_C ...
- Windows Sockets Error Codes
https://msdn.microsoft.com/en-us/library/windows/desktop/ms740668(v=vs.85).aspx Most Windows Sockets ...
- codeforces 696B Puzzles 树形概率计算
题意:给一棵有根树,从根节点深搜,每次随机走,问每个点的dfs序的期望是多少 分析:对于每一个点,它的所有祖先节点dfs序肯定在它之前,它所在的子树的节点一定在它后面, 剩下的是既不是子树又不是祖先的 ...
- 从python run 和python unittest两种eclipse运行方式深入理解if __name__ == "__main__"
在写一个简单的python测试程序的时候,发现eclipse中Run as "Python run 和 Python unittest”结果不一样?为什么会不一样? 先贴一下代码段: # - ...
- 45度地图遮挡问题解决方案(cocos2d-x)
最近一直在做45度斜视角游戏,也就是isometric等容地图,俗称2.5D.地图上物体的前后遮挡是我遇到的第一个问题,总结一下处理方法. 遮挡问题(不知道术语),就是比如一个角色站在树后面,那么树要 ...