NPOI, 讀取xls文件(Excel2003及以前的版本) (NPOI.dll+Ionic.Zip.dll) http://npoi.codeplex.com/html
EPPlus, 讀取xlsx文件(Excel2007版本) (EPPlus.dll) http://epplus.codeplex.com/app
本文中只實現了Excel文件的讀取,實際上,這兩個控件均支持對其內容,格式,公式等進行修改,這些複雜功能尚無需求,因此沒有實現this
讀取接口IExcel:spa
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文件實現:code
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文件實現:orm
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();
}
調用類:xml
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;
}
調用:htm
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");blog
//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