C#读取Excel数据
/// <summary>
/// 返回Excel数据源
/// </summary>
/// <param name="filePath">文件路径</param>
/// <returns></returns>
public static System.Data.DataTable ReadExcel(string filePath)
{
//strConn = "Provider=Microsoft.Jet. OLEDB.4.0;Data Source=C:\\Erp1912.xls;Extended Properties='Excel8.0;HDR=Yes;IMEX=1'";
//通过Imex=1来把混合型作为文本型读取,避免null值
System.Data.DataTable tab = new System.Data.DataTable();
string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Excel 8.0;data source=" + filePath;
OleDbConnection myConn = new OleDbConnection(strCon);
try
{
myConn.Open();
//获取所有Sheet名称
DataTable sheetNames = myConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
string strCom = string.Format(" SELECT * FROM [{0}]", sheetNames.Rows[0]["TABLE_NAME"]);
OleDbDataAdapter myCommand = new OleDbDataAdapter(strCom, myConn);
myCommand.Fill(tab);
return tab;
}
catch
{
return null;
}
finally
{
myConn.Close();
}
}
#endregion
}
/// 返回Excel数据源
/// </summary>
/// <param name="filePath">文件路径</param>
/// <returns></returns>
public static System.Data.DataTable ReadExcel(string filePath)
{
//strConn = "Provider=Microsoft.Jet. OLEDB.4.0;Data Source=C:\\Erp1912.xls;Extended Properties='Excel8.0;HDR=Yes;IMEX=1'";
//通过Imex=1来把混合型作为文本型读取,避免null值
System.Data.DataTable tab = new System.Data.DataTable();
string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Excel 8.0;data source=" + filePath;
OleDbConnection myConn = new OleDbConnection(strCon);
try
{
myConn.Open();
//获取所有Sheet名称
DataTable sheetNames = myConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
string strCom = string.Format(" SELECT * FROM [{0}]", sheetNames.Rows[0]["TABLE_NAME"]);
OleDbDataAdapter myCommand = new OleDbDataAdapter(strCom, myConn);
myCommand.Fill(tab);
return tab;
}
catch
{
return null;
}
finally
{
myConn.Close();
}
}
#endregion
}