2

Excelファイルを参照してグリッドビューに表示するC#プロジェクトを行ってきました。ただし、理解できないエラーメッセージがあります。誰かがこれについて私を助けてくれませんか。

これは私が使用したコードです:

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)."
4

2 に答える 2

2

経由で Excel に接続しようとしていますSqlConnection

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(); 
}
于 2012-05-25T11:03:17.143 に答える
0

ODBC または JET 接続にはSqlConnectionまたはを使用できません。またはSqlDataAdapterを使用します。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); 
       }
   } 
}
于 2012-05-25T11:04:28.607 に答える