我有一个示例代码,我想用C#语言在Visual Studio 2022中的Winform应用程序中使用C#语言读取DataGridView中Excel文件的内容,但是Excel文件的内容没有显示在DataGridView中。我使用 Windows 11。
为了测试 Excel 文件的内容,我可以使用控制台应用程序轻松读取它并将其显示在程序中,但我无法在 DataGridView 中执行相同的操作。我记得几个月前我用同样的代码从Excel文件中读取数据并在程序中使用它,但现在我不能,我不知道问题出在哪里。
我将 Visual Studio 2022 更新到最新版本。问题可能与更新有关吗?
using System;
using System.Data;
using System.Data.OleDb;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
// Declare the connection and the adapter objects
private OleDbConnection conn;
private OleDbDataAdapter adapter;
// Declare the DataSet object to hold the data from the Excel file
private DataSet ds;
// Declare the path and the name of the Excel file
private string path = @"C:\\Users\\Hamed\\Desktop\\ConsoleApp1\\sample.xlsx";
private string fileName = "sample.xlsx";
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// Create the connection string based on the file extension
string connectionString = "";
string fileExtension = System.IO.Path.GetExtension(fileName);
if (fileExtension == ".xls")
connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
else if (fileExtension == ".xlsx")
connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
// Create the connection and the adapter objects
conn = new OleDbConnection(connectionString);
adapter = new OleDbDataAdapter("SELECT * FROM [Sheet1$A1:C10]", conn);
// Create the DataSet object and fill it with the data from the Excel file
ds = new DataSet();
adapter.Fill(ds);
// Bind the data to the DataGridView
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = ds.Tables[0];
}
private void button1_Click(object sender, EventArgs e)
{
// Create the command builder object to generate the update commands
OleDbCommandBuilder cmdBuilder = new OleDbCommandBuilder(adapter);
// Update the Excel file with the changes made in the DataGridView
adapter.Update(ds.Tables[0]);
// Show a message to confirm the update
MessageBox.Show("The Excel file has been updated.");
}
}
}
我制作了一个名为dataGridView1的DataGridView,然后编写了这段代码。我没有进行任何其他设置。我使用 .NET 8 和 7 以及 .NET Framework 4.8 进行了测试,但它不起作用。我的问题是 DataGridView 中的内容显示没有任何错误
我工作的问题是我忘记将“Form1_Load”放在“Events > Load”部分中,这就是“Form1_Load”根本没有执行的原因。
注意:确保已为您安装 OleDB 的官方 Microsoft 软件包。要安装它,您可以转到 Nugget Package Manager 并安装它。