我在数据集中获得excel文件数据,但在数据集数据中重复,excel文件有四个记录,数据集显示8条记录。每条记录都是重复的。我的文件扩展名是.xlsx。 我做错了什么?
这是我的代码:
public static DataSet GenerateExcelData(string path)
{
OleDbConnection oledbConn = null;
try
{
/* connection string to work with excel file. HDR=Yes - indicates
that the first row contains columnnames, not data. HDR=No - indicates
the opposite. "IMEX=1;" tells the driver to always read "intermixed"
(numbers, dates, strings etc) data columns as text.
Note that this option might affect excel sheet write access negative. */
if (Path.GetExtension(path) == ".xls")
{
oledbConn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"");
}
else if (Path.GetExtension(path) == ".xlsx")
{
//oledbConn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1;';");
oledbConn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;");
}
oledbConn.Open();
OleDbCommand cmd = new OleDbCommand(); ;
OleDbDataAdapter oleda = new OleDbDataAdapter();
DataSet ds = new DataSet();
cmd.Connection = oledbConn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM [Sheet1$]";
oleda = new OleDbDataAdapter(cmd);
oleda.Fill(ds);
//EDIT: Below lines are duplicate
//oleda = new OleDbDataAdapter(cmd);
//oleda.Fill(ds);
return ds;
}
// need to catch possible exceptions
catch (Exception ex)
{
throw ex;
}
finally
{
oledbConn.Close();
}
}
答案 0 :(得分:2)
您正在填充数据集两次。
答案 1 :(得分:2)
oleda = new OleDbDataAdapter(cmd);
oleda.Fill(ds);
为什么这段代码重复了两次?我认为这会导致错误
答案 2 :(得分:1)
您正在填充数据集两次。
oleda = new OleDbDataAdapter(cmd);
oleda.Fill(ds);
oleda = new OleDbDataAdapter(cmd);
oleda.Fill(ds);
你可能忘了你已经添加了两行。您只需要删除重复的代码。