【问题标题】:How to import an excel file to DataGridView in C#如何在 C# 中将 Excel 文件导入 DataGridView
【发布时间】:2019-02-18 14:43:28
【问题描述】:

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

我打开了对话框文件并搜索了 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();
}

【问题讨论】:

  • 您的问题不清楚。首先,如果您想从 Excel 文件中获取“选定”单元格……那么您将不得不与“Excel”对话。当您“导入”一个 excel 文件时,选定的单元格信息将不可用。此外,打开 excel 然后立即抓取选定的单元格……这似乎是一件奇怪的事情,因为您不可能(在每种情况下)知道那些“选定”的单元格是什么。 excel 文件的打开“暗示”用户将选择单元格并“然后”通过某种机制发出信号,表明应该执行复制。
  • 我猜你可能让这变得比它必须的更复杂。您是否考虑过制作两 (2) 个网格。最初,两个网格都包含与您已有的原始 Excel 数据相同的“副本”。然后……执行您描述的操作会容易得多,因为您会“知道”选择了哪些单元格。此外,必须与 excel 库交互才能访问 excel 变量,这将是更多的工作。只是一个想法。
  • 您可以使用 OpenXml 读取 Excel 中选定的行/单元格。 stackoverflow.com/questions/3321082/…

标签: c# excel winforms datagridview


【解决方案1】:

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

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,以便更容易放入数据网格视图中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-22
    • 1970-01-01
    相关资源
    最近更新 更多