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的更多相关文章

  1. NPOI操作Excel辅助类

    /// <summary> /// NPOI操作excel辅助类 /// </summary> public static class NPOIHelper { #region ...

  2. NPOI操作excel之写入数据到excel表

    在上一篇<NPOI操作excel之读取excel数据>我们把excel数据写入了datatable中,本篇就讲如何把datatable数据写入excel中. using System; u ...

  3. C#开发中使用Npoi操作excel实例代码

    C#开发中使用Npoi操作excel实例代码 出处:西西整理 作者:西西 日期:2012/11/16 9:35:50 [大 中 小] 评论: 0 | 我要发表看法 Npoi 是什么? 1.整个Exce ...

  4. 用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 ...

  5. C# 如何使用NPOI操作Excel以及读取合并单元格等

    C#操作Excel方法有很多,以前用的需要电脑安装office才能用,但因为版权问题公司不允许安装office.所以改用NPOI进行Excel操作,基本上一些简单的Excel操作都没有问题,读写合并单 ...

  6. 用NPOI操作EXCEL-锁定列CreateFreezePane()

    public void ExportPermissionRoleData(string search, int roleStatus) { var workbook = new HSSFWorkboo ...

  7. .NET 通过 NPOI 操作 Excel

    目录 .NET 通过 NPOI 操作 Excel 第一步:通过 NuGet 获取 NPOI 包并引入程序集 第二步:引入 NPOI 帮助类 第三步:在程序中调用相应的方法对数据进行导出导入操作 将 D ...

  8. 2.6.2 用NPOI操作EXCEL--设置密码才可以修改单元格内容

    2.6.2 用NPOI操作EXCEL--设置密码       有时,我们可能需要某些单元格只读,如在做模板时,模板中的数据是不能随意让别人改的.在Excel中,可以通过“审阅->保护工作表”来完 ...

  9. 使用NPOI操作Excel文件及其日期处理

    工作中经常遇到需要读取或导出Excel文件的情况,而NPOI是目前最宜用.效率最高的操作的Office(不只是Excel哟)文件的组件,使用方便,不详细说明了. Excel工作表约定:整个Excel表 ...

  10. [Solution] NPOI操作Excel

    NPOI 是 POI 项目的 .NET 版本.POI是一个开源的Java读写Excel.WORD等微软OLE2组件文档的项目.使用 NPOI 你就可以在没有安装 Office 或者相应环境的机器上对 ...

随机推荐

  1. UVa 11889 (GCD) Benefit

    好吧,被大白书上的入门题给卡了.=_=|| 已知LCM(A, B) = C,已知A和C,求最小的B 一开始我想当然地以为B = C / A,后来发现这时候的B不一定满足gcd(A, B) = 1 A要 ...

  2. bzoj3555: [Ctsc2014]企鹅QQ

    将字符串hash.不难写.然而1.注意用longlong2.数组大小注意...3.似乎别人都用的unsigned long long ?. #include<cstdio> #includ ...

  3. FileZilla无法确定拖放操作的目标,由于shell未正确安装

    天有不测风云,突然间,用filezilla下载ftp上的文件到桌面的时候,提示"无法确定拖放操作目标.由于shell未正确安装" 解决办法很简单,执行如下几步就OK了 1.在CMD ...

  4. 基于phpExcel写的excel类

    <?php /* * 类的功能 * 传入二位数组导出excel * 传入excel 导出二位数组 * @author mrwu */ require('PHPExcel.php'); requi ...

  5. Mybatis学习——一对多关联表查询

    1.实体类 public class Student { private int id; private String name; } public class Classes { private i ...

  6. POJ 2352 Stars(HDU 1541 Stars)

    Stars Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 41521   Accepted: 18100 Descripti ...

  7. 解决: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 ...

  8. Android:实现一种浮动选择菜单的效果

    总结如何实现Android浮动层,主要是dialog的使用. 自定义一个类继承自Dialog类,然后在构造方法中,定义这个dialog的布局和一些初始化信息. 案例1: public class Me ...

  9. Int.Parse()、Convert.toInt32()和(int)区别

    通过网上的查询从而了解了Int.Parse().Convert.toInt32()和(int)区别. 一.定义上的差别 int类型表示一种整型,.NET Framework 类型为 System.In ...

  10. <转>浅谈DNS体系结构:DNS系列之一

    浅谈DNS体系结构 DNS是目前互联网上最不可或缺的服务器之一,每天我们在互联网上冲浪都需要DNS的帮助.DNS服务器能够为我们解析域名,定位电子邮件服务器,找到域中的域控制器……面对这么一个重要的服 ...