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

标签 c# .net sql-server gridview datagridview

我一直在做一个 C# 项目,在该项目中我在 GridView 中浏览和查看 Excel 文件。但是,有一条我不明白的错误消息。有人可以帮我解决这个问题吗?

这是我使用的代码:

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

最佳答案

您正在尝试通过 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(); 
}

关于c# - SQLException 未处理。在 GridView 中查看 Excel 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10753219/

相关文章:

c# - 根据收件人自定义电子邮件

c# - 为什么使用 .net 4 最终版本的 MEF 后 GetExportedValues<T>() 不再起作用?

c# - ELMAH 在哪里保存数据?

sql-server - 用记录计算一年中的天数

sql-server - 如何通过 BIDS 将新的维度属性添加到现有维度

C# 为什么在随机数中得到一个零数

c# - 在另一个 Web API 中管理 Web API JWT token 的最佳实践

c# - .net 世界中的 EDI 等价物

c# - 何时使用 IEnumerable 与 IObservable?

.net - Entity Framework 函数导入参数类型在从数据库更新模型时重置