C#读取excl(兼容office多种版本)

 

要求:导入excl引用了using System.Data.OleDb,需要安装一个office

兼容原理:office导入字符串会因为版本改变,捕获异常的方式进行切换

#region 读取Excel数据到DataSet iqsir 2015-11-21

/// <summary>
/// 读取Excel数据到DataSet
/// </summary>
/// <param name="filepath">excel带路径</param>
/// <param name="tabindex">取第几个表</param>
/// <param name="hdr">第一行是列名而不是数据</param>
/// <returns>dataset</returns>
protected DataSet ReadExcel(string filepath, int tabindex, string hdr)
{
string meg = "";
DataSet ds;
string strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='{0}';Extended Properties='Excel 12.0;HDR=" + hdr + ";IMEX=1'";
string strConnection1 = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source='{0}';Extended Properties='Excel 8.0;HDR=" + hdr + ";IMEX=1'";
//备注: "HDR=yes;"是说Excel文件的第一行是列名而不是数据,"HDR=No;"正好与前面的相反。
// "IMEX=1 "如果列中的数据类型不一致,使用"IMEX=1"可必免数据类型冲突。

// 当 IMEX = 0 时为“汇出模式”,这个模式开启的 Excel 档案只能用来做“写入”用途。

//当 IMEX = 1 时为“汇入模式”,这个模式开启的 Excel 档案只能用来做“读取”用途。
//当 IMEX = 2 时为“连結模式”,这个模式开启的 Excel 档案可同时支援“读取”与“写入”用途。


strConnection = string.Format(strConnection, filepath);

string msgConst = "打开excel连接字符串错误,解决方法:1安装offic2010+,2更改c/windows/temp文件夹权限为everyone完全控制";

try
{
OleDbConnection con = new OleDbConnection(strConnection);
try
{
con.Open();
DataTable schema = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
//下面取得表名

string strTableName = schema.Rows[tabindex]["TABLE_NAME"].ToString();
strTableName = strTableName.Substring(0, strTableName.IndexOf('$') + 1);
OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM [" + strTableName + "]", con);
ds = new DataSet();
da.Fill(ds);
da.Dispose();
return ds;
}
catch (Exception exmsg1)
{
string strMsg = msgConst + exmsg1;
throw new Exception(strMsg);

}
finally
{
con.Close();
}


}
catch (Exception ex)
{

try
{

OleDbConnection con = new OleDbConnection(string.Format(strConnection1, filepath));
try
{
con.Open();
DataTable schema = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
//下面取得表名

string strTableName2 = schema.Rows[tabindex]["TABLE_NAME"].ToString();

strTableName2 = strTableName2.Substring(0, strTableName2.IndexOf('$') + 1);
OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM [" + strTableName2 + "]", con);
ds = new DataSet();
da.Fill(ds);
da.Dispose();
return ds;
}
catch (Exception exmsg2)
{
string strMsg2 = msgConst + exmsg2;
throw new Exception(strMsg2);
}
finally
{
con.Close();
}

}
catch (Exception ex1)
{

throw new Exception("连接方案2错误1:" + ex1.Message + " 错误2:可能文件名错误");
}


}


}
#endregion

posted @ 2016-12-14 10:55  下页小希  阅读(1684)  评论(0编辑  收藏  举报