/// <summary>
/// 读取xls中数据类
/// </summary>
public class ExcelOutData
{
/// <summary>
/// 读取url的xls
/// </summary>
/// <param name="url"></param>
public static DataSet GetData(string url)
{
//excel 2003
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + url + ";Extended Properties=Excel 8.0;";
//excel 2007
if(Path.GetExtension(url).ToUpper()==".XLSX")
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + url + ";Extended Properties=\"Excel 12.0;HDR=YES\"";
OleDbConnection conn = new OleDbConnection(strConn);
DataSet ds = ds = new DataSet();
try
{
conn.Open();
System.Data.DataTable tables = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
for (int i = 0; i < tables.Rows.Count; i++)
{
System.Data.DataTable dt = new System.Data.DataTable(tables.Rows[i][2].ToString());
OleDbDataAdapter oada = new OleDbDataAdapter("select * from [" + tables.Rows[i][2] + "]", strConn);
oada.Fill(dt);
ds.Tables.Add(dt);
}
}
catch (Exception ex){
throw;
}
finally {
if (conn.State == ConnectionState.Open)
conn.Close();
}
return ds;
}
}
C#中获取Excel文件的表名
最新推荐文章于 2021-03-03 09:57:19 发布