}
读取EXCEL导入C# 返回DS
public DataSet ReadExcel(string filePath)
{
if (filePath=="")
{
return null;
}
//文件格式不正确
if (!filePath.Substring(filePath.LastIndexOf('.')).ToUpper().Equals(".XLSX"))
{
return null;
}
//找不到文件
if (!File.Exists(filePath))
{
return null;
}
DataSet ds = null;
try
{
ds = new DataSet();
string strConn = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'", filePath);
using (OleDbConnection conn = new OleDbConnection(strConn))
{
conn.Open();
//获取第一个SheetName
//包含excel中表名的字符串数组
DataTable SheetList = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" });
//找不到数据
if (SheetList.Rows.Count <= 0)
{
return null;
}
string TableName = Convert.ToString(SheetList.Rows[0]["TABLE_NAME"]);
OleDbDataAdapter odda = new OleDbDataAdapter("select * from [" + TableName + "]", strConn);
odda.Fill(ds, TableName);
conn.Close();
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
return ds;
}