【c#操作office】--OleDbDataAdapter 与OleDbDataReader方式读取excel,并转换为datatable

时间:2023-03-09 16:40:25
【c#操作office】--OleDbDataAdapter 与OleDbDataReader方式读取excel,并转换为datatable

OleDbDataAdapter方式:

        /// <summary>
/// 读取excel的表格放到DataTable中 ---OleDbDataAdapter
/// </summary>
/// <param name="strSql"></param>
        /// <param name="excelpath">excel路径</param>
/// <returns>datatable</returns>
public static DataTable readexcel(string excelpath,string strSql)
{
OleDbConnection objConn = null;
DataTable dt = new DataTable();
try
{
string excelConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data source=" + excelpath + ";Excel 8.0;HDR=NO;IMEX=1";//HDR=YES第一行是标题,NO第一行不是标题;IMEX=1表示导入模式,这个模式开启的 Excel 档案只能用来做“写入”用途,还有个重要作用:强制将混合数据转换为文本,可读出excel的数字型的内容。
objConn = new OleDbConnection(excelConn);
objConn.Open();
OleDbCommand objCmd = new OleDbCommand(strSql, objConn);
OleDbDataAdapter adr = new OleDbDataAdapter();
adr.SelectCommand = objCmd;
adr.Fill(dt);
objConn.Close();
return dt;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return null;
}
}

OleDbDataReader 方式:

        /// <summary>
/// 读取excel的表格放到DataTable中 ---OleDbDataReader
/// </summary>
/// <param name="strSql"></param>
        /// <param name="excelpath">excel路径</param>
/// <returns>datatable</returns>
public static DataTable readexcel(string excelpath,string strSql)
{
string excelConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data source=" + excelpath + ";Excel 8.0;HDR=NO;IMEX=1";//HDR=YES第一行是标题,NO第一行不是标题;IMEX=1表示导入模式,这个模式开启的 Excel 档案只能用来做“写入”用途,还有个重要作用:强制将混合数据转换为文本,可读出excel的数字型的内容。
DataTable dt = new DataTable();
try
{
using (OleDbConnection connection = new OleDbConnection(excelConn))
{
OleDbCommand command = new OleDbCommand(strSql, connection);
connection.Open();
OleDbDataReader reader;
reader = command.ExecuteReader();
dt.Load(reader); //直接把reader转换为datatable
reader.Close();
}
return dt;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return null;
}
}

从上述两个例子不难看出,其实excel也相当于一个数据库,读取excel的sql语句如:string strSql = "Select  *  From  [sheet1$A10:L24]";//读取sheet1工作表A10到L24区域的内容

类似的,读取oracle等数据库,只需把数据库引擎等改为相应的类型就可以了。