如何读取EXCEL到DataTable,需要从指定的行列读取
1个回答
展开全部
public static DataSet ImportExcel(string file)
{
FileInfo fileInfo = new FileInfo(file);
if (!fileInfo.Exists)
return null;
string strConn = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + file + ";Extended Properties='Excel 8.0;HDR=NO;IMEX=1'";
OleDbConnection objConn = new OleDbConnection(strConn);
DataSet dsExcel = new DataSet();
try
{
objConn.Open();
string strSql = "select TOP 10 * from [Sheet1$]"; //修改这条SQL,应该能实现从第几条到第几条
OleDbDataAdapter odbcExcelDataAdapter = new OleDbDataAdapter(strSql, objConn);
odbcExcelDataAdapter.Fill(dsExcel);
return dsExcel;
}
catch (Exception ex)
{
throw ex;
}
}
或者
private DataTable FromExcel()
{
string strConn;
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=lieche.xls;Extended Properties='Excel 8.0;HDR=False;IMEX=1'";
OleDbConnection OleConn = new OleDbConnection(strConn);
OleConn.Open();
String sql = "SELECT * FROM [Sheet1$]";//改变这sql语句取你需要的
OleDbDataAdapter OleDaExcel = new OleDbDataAdapter(sql, OleConn);
DataSet OleDsExcle = new DataSet();
OleDaExcel.Fill(OleDsExcle, “lieche”);
OleConn.Close();
return OleDsExcle.table[0];
}
{
FileInfo fileInfo = new FileInfo(file);
if (!fileInfo.Exists)
return null;
string strConn = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + file + ";Extended Properties='Excel 8.0;HDR=NO;IMEX=1'";
OleDbConnection objConn = new OleDbConnection(strConn);
DataSet dsExcel = new DataSet();
try
{
objConn.Open();
string strSql = "select TOP 10 * from [Sheet1$]"; //修改这条SQL,应该能实现从第几条到第几条
OleDbDataAdapter odbcExcelDataAdapter = new OleDbDataAdapter(strSql, objConn);
odbcExcelDataAdapter.Fill(dsExcel);
return dsExcel;
}
catch (Exception ex)
{
throw ex;
}
}
或者
private DataTable FromExcel()
{
string strConn;
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=lieche.xls;Extended Properties='Excel 8.0;HDR=False;IMEX=1'";
OleDbConnection OleConn = new OleDbConnection(strConn);
OleConn.Open();
String sql = "SELECT * FROM [Sheet1$]";//改变这sql语句取你需要的
OleDbDataAdapter OleDaExcel = new OleDbDataAdapter(sql, OleConn);
DataSet OleDsExcle = new DataSet();
OleDaExcel.Fill(OleDsExcle, “lieche”);
OleConn.Close();
return OleDsExcle.table[0];
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询