using
System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.OleDb;
namespace pro
... {
public class MyExcel
...{
//连接字符串
public const string Define_ConnectStringFormat = "Provider=Microsoft.Jet.OleDb.4.0;data source={0};Extended Properties='Excel 8.0; HDR=YES; IMEX=1'";
//SQL格式字符串
public const string Define_SQLStringFormat = "Select * from [{0}$]";
//Excel操作类
private OleDbConnection conn = null;
private OleDbDataAdapter adapter = null;
/**//// <summary>
/// 打开Excel
/// </summary>
/// <param name="excelFilename">Excel名</param>
/// <returns>true:成功 false:失败</returns>
///
internal bool OpenExcel(string excelFilename)
...{
try
...{
//生成连接字符串
string strConn = string.Format(MyExcel.Define_ConnectStringFormat, excelFilename);
conn = new OleDbConnection(strConn);
return true;
}
catch
...{
return false;
}
}
/**//// <summary>
/// 取得Sheet的内容
/// </summary>
/// <param name="sheetName">Sheet名</param>
/// <returns>DataTable</returns>
internal DataTable GetSheet(string sheetName)
...{
try
...{
string strSQL = string.Format(MyExcel.Define_SQLStringFormat, sheetName);
adapter = new OleDbDataAdapter(strSQL, conn);
DataSet dataSet = new DataSet();
conn.Open();
adapter.Fill(dataSet, sheetName);
DataTable dataTable = dataSet.Tables[sheetName];
conn.Close();
return dataTable;
}
catch
...{
return null;
}
}
}
}
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.OleDb;
namespace pro
... {
public class MyExcel
...{
//连接字符串
public const string Define_ConnectStringFormat = "Provider=Microsoft.Jet.OleDb.4.0;data source={0};Extended Properties='Excel 8.0; HDR=YES; IMEX=1'";
//SQL格式字符串
public const string Define_SQLStringFormat = "Select * from [{0}$]";
//Excel操作类
private OleDbConnection conn = null;
private OleDbDataAdapter adapter = null;
/**//// <summary>
/// 打开Excel
/// </summary>
/// <param name="excelFilename">Excel名</param>
/// <returns>true:成功 false:失败</returns>
///
internal bool OpenExcel(string excelFilename)
...{
try
...{
//生成连接字符串
string strConn = string.Format(MyExcel.Define_ConnectStringFormat, excelFilename);
conn = new OleDbConnection(strConn);
return true;
}
catch
...{
return false;
}
}
/**//// <summary>
/// 取得Sheet的内容
/// </summary>
/// <param name="sheetName">Sheet名</param>
/// <returns>DataTable</returns>
internal DataTable GetSheet(string sheetName)
...{
try
...{
string strSQL = string.Format(MyExcel.Define_SQLStringFormat, sheetName);
adapter = new OleDbDataAdapter(strSQL, conn);
DataSet dataSet = new DataSet();
conn.Open();
adapter.Fill(dataSet, sheetName);
DataTable dataTable = dataSet.Tables[sheetName];
conn.Close();
return dataTable;
}
catch
...{
return null;
}
}
}
}
调用:
使用命名空间:
using pro;
继承类:
protected MyExcel ex = new MyExcel();
打开excel文件:
ex.OpenExcel("book1.xls");
读取Excel内容:
DataTable dt1 = ex.GetSheet("sheet1");