SQLException未处理。在GridView中查看Excel文件

时间:2012-05-25 10:57:40

标签: c# .net sql-server gridview datagridview

我一直在做一个C#项目,在那里我浏览并查看Excel文件到gridview中。但是,有一条错误消息,我不明白。有人可以帮我解决这个问题。

这是我使用的代码:

private void buttonUpload_Click(object sender, EventArgs e)
{
    string connectionString = String.Format(@"Data Source={0};Extended Properties=""Excel 8.0;HDR=YES;IMEX=1;""", textBoxFileName.Text);

    string query = String.Format("select * from [{0}$]", "Sheet1");

    SqlDataAdapter dataAdapter = new SqlDataAdapter(query, connectionString);

    DataSet dataSet = new DataSet();

    dataAdapter.Fill(dataSet);

    dataGridView1.DataSource = dataSet.Tables[0];
}

这是错误消息:

"A network-related or instance-specific error occurred while establishing 
a connection to SQL Server. The server was not found or was not accessible. 
Verify that the instance name is correct and that SQL Server is configured 
to allow remote connections. 
(provider: SQL Network Interfaces, 
error: 26 - Error Locating Server/Instance Specified)."

2 个答案:

答案 0 :(得分:2)

您正尝试通过SqlConnection连接到Excel。

要连接到Excel,请使用OleDBConnection

private void buttonUpload_Click(object sender, EventArgs e)
{
   string connectionString = String.Format(@"Data Source={0};Extended Properties=""Excel 8.0;HDR=YES;IMEX=1;""", textBoxFileName.Text)
   var objConn = new OleDbConnection(connectionString);

   objConn.Open(); 

   OleDbCommand objCmdSelect = new OleDbCommand("SELECT * FROM [Sheet1$]", objConn);

   OleDbDataAdapter objAdapter1 = new OleDbDataAdapter(); 

   objAdapter1.SelectCommand = objCmdSelect; 

   DataSet objDataset1 = new DataSet(); 

   objAdapter1.Fill(objDataset1); 

   objConn.Close(); 
}

答案 1 :(得分:0)

您不能将SqlConnectionSqlDataAdapter用于ODBC或JET连接。使用OleDbConnectionOleDbDataAdapter

请确保及时处理连接和资源。建议在此处使用using语句。

private void buttonUpload_Click(object sender, EventArgs e)
{
   string connectionString = String.Format(@"Data Source={0};Extended Properties=""Excel 8.0;HDR=YES;IMEX=1;""", textBoxFileName.Text);
   DataSet objDataset1 = new DataSet();

   using (OleDbConnection objConn = new OleDbConnection(connectionString))
   {
       objConn.Open(); 

       using (OleDbCommand objCmdSelect = new OleDbCommand("SELECT * FROM [Sheet1$]", objConn))
       using (OleDbDataAdapter objAdapter1 = new OleDbDataAdapter())
       {
           objAdapter1.SelectCommand = objCmdSelect;    
           objAdapter1.Fill(objDataset1); 
       }
   } 
}