c# - 如何在 C# 中将 excel 文件导入 DataGridView

标签 c# excel winforms datagridview

我正在努力将 excel 文件导入我的 DataGridView。但是如何在我的 DataGridView 中导入包含选定行和列的 excel 文件?我只有将整个 excel 文件加载到我的 DataGridView 的代码,我是 C# 的新手

我打开了 dialogfile 并搜索 excel 文件,假设我的数据从 C:34,D:34E:34 开始,在一列或数据中具有 EmploayeeName 并选择前 24 行并将其加载到我的 DataGridView

提前感谢您的帮助! 这是我仅有的东西:(

private void OpenFile_Click(object sender, EventArgs e)
{
    OpenFileDialog fdlg = new OpenFileDialog();
    fdlg.Title = "Select file";
    fdlg.InitialDirectory = @"c:\";
    fdlg.FileName = txtFileName.Text;
    fdlg.Filter = "Excel Sheet(*.xlsx)|*.xlsx|All Files(*.*)|*.*";
    fdlg.FilterIndex = 1;
    fdlg.RestoreDirectory = true;
    if (fdlg.ShowDialog() == DialogResult.OK)
    {
        path = textBox1.Text;
        txtFileName.Text = fdlg.FileName;

        Application.DoEvents();
    }
}

private void LoadExcel_Click(object sender, EventArgs e)
{
    System.Data.OleDb.OleDbConnection MyConnection;
    System.Data.DataSet DtSet;
    System.Data.OleDb.OleDbDataAdapter MyCommand;
    MyConnection = new System.Data.OleDb.OleDbConnection(@"provider=Microsoft.Jet.OLEDB.4.0;Data Source='c:\csharp.net-informations.xls';Extended Properties=Excel 8.0;");
    MyCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection);
    MyCommand.TableMappings.Add("Table", "Net-informations.com");
    DtSet = new System.Data.DataSet();
    MyCommand.Fill(DtSet);
    dgrdReciver.DataSource = DtSet.Tables[0];
    MyConnection.Close();
}

最佳答案

好吧,我会先获取文件的路径,然后使用这样的文件流:

string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), file.Name);


    using (Stream fileStream = File.OpenWrite(path))
    {

        // do what you want with the file stream.
        sftp.DownloadFile(remoteDirectory + "/" + file.Name, fileStream);



    }

我什至会将该数据放入 SQL Server,以便更容易放入数据 GridView 。

关于c# - 如何在 C# 中将 excel 文件导入 DataGridView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52320902/

相关文章:

c# - 禁用组合框中的特定项目

c# - 整数无穷大的最佳替代方案

c# - 具有复杂相等性的 HashSet

c# - 如何获得事件的订阅者?

c# - MySQL 与另外两个表一起创建一个表并使用 C# WinForms 添加记录

vba - 无法关闭打开的 excel 工作簿

c# - 从单元格中托管的控件退出编辑模式

java - 在 SIT 上运行时 Apache POI 错误

vba - Range.Find 在隐藏且属于过滤器的范围上失败

c# - 如何以编程方式将节点添加到 TreeView ?