使用OLEDB来读取EXCEL的原因很简单,只是因为我感觉代码量不多。代码已经本地测试通过。
public class OlEDBHelp
{public DataSet ExcelToDataSet(string path,string tableName = "table1"){DataSet ds = new DataSet();string strConn = string.Format($"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={path};Extended Properties=Excel 8.0;");OleDbConnection conn = new OleDbConnection(strConn);conn.Open();string strExcel = string.Format($"select * from [{conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null).Rows[0][2].ToString().Trim()}]");//自动获取第一个sheet页名称OleDbDataAdapter myCommand = new OleDbDataAdapter(strExcel, strConn);try{myCommand.Fill(ds, tableName);}catch (Exception ex){throw new Exception(ex.ToString());}finally{conn.Close();} return ds;}
}
使用方式如下所示:
string path = string.Format(@"C:\Users\wangxc\Desktop\MyExcel.xls");
OlEDBHelp oh = new OleHelp();
DataSet ds = oh.ExcelToDataSet(path);