c#用oledb 进行excel数据导入失败,只有data[0]中有x和y的数据

OpenFileDialog openDG = new OpenFileDialog();
openDG.Title = "打开Excel表格";
openDG.Filter = "Excel表格(*.xls)|*.xls|CSV格式(*.csv)|*.csv|所有文件(*.*)|*.*";
openDG.ShowDialog();
string filename;
filename = openDG.FileName;
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filename + ";Extended Properties='Excel 8.0;HDR=NO;IMEX=1'";
oledbcConnection = new OleDbConnection(strConn);
oledbcConnection.Open();

try
{
string strExcel = "";
OleDbDataAdapter myCommand = null;
strExcel = "select * from [Book2$]";
myCommand = new OleDbDataAdapter(strExcel, strConn);
DataSet ds = new DataSet();
myCommand.Fill(ds, "Book2");
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
// if (ds.Tables[0].Rows.Count >0)
{
//将Excel表中的数据存储到数组

data[i].x = int.Parse(ds.Tables[0].Rows[i][0].ToString());
data[i].y = int.Parse(ds.Tables[0].Rows[i][1].ToString());
data[i].p[0] = float.Parse(ds.Tables[0].Rows[i][2].ToString());
data[i].p[1] = float.Parse(ds.Tables[0].Rows[i][3].ToString());
data[i].p[2] = float.Parse(ds.Tables[0].Rows[i][4].ToString());
data[i].n[0] = double.Parse(ds.Tables[0].Rows[i][5].ToString());
data[i].n[1] = double.Parse(ds.Tables[0].Rows[i][6].ToString());
data[i].n[2] = double.Parse(ds.Tables[0].Rows[i][7].ToString());
}

}
catch (Exception ex)
{
return;
}
finally
{
oledbcConnection.Close();
oledbcConnection.Dispose();

第1个回答  2015-11-01
用sql不方便,还是用导入dll吧,忘记叫什么名字了...
第2个回答  2015-11-02
把try catch去掉再运行看哪里有错吧。追问

data[i].p[0] = float.Parse(ds.Tables["Book2"].Rows[i][2].ToString());
未将对象引用设置到对象的实例。

追答

那说明相应位置没数据嘛,先判断是否为null,不为null再ToString。

第3个回答  2015-11-01
用sql不方便,还是用导入dll吧,忘记叫什么名字了...
第4个回答  2015-11-02
把try catch去掉再运行看哪里有错吧。追问

data[i].p[0] = float.Parse(ds.Tables["Book2"].Rows[i][2].ToString());
未将对象引用设置到对象的实例。

追答

那说明相应位置没数据嘛,先判断是否为null,不为null再ToString。

相似回答