简体   繁体   中英

How to import an excel file to DataGridView in C#

I'am working for importing an excel file into my DataGridView . But how do I import excel file with selected rows and column in my DataGridView ? I have only code for load the whole excel file to my DataGridView , I'm new in C#

I have open dialogfile and search for the excel file, let's say my data starts in C:34,D:34 and E:34 in one column or data that have a EmploayeeName and select the top 24 rows and load it to my DataGridView .

Thank you in advance for giving a hand! This is the only stuff that I have :(

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();
}

Well, I would start off by getting the path of the file and then using a file stream like this:

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);



    }

I would even put that data into a SQL Server so it is easier to put into a data grid view.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM