How to import excell file to DataGridView from a specific row in C#?

I want to import excell value from 2nd row and on to the DataGridView but dont know how. If possible I want to keep the current existing data value in datagridview is not deleted so the imported data just added after.

this is the current result of the export from the datagridview. I want it to become template to import so the imported data only reads from 2nd row and on. I dont understand at all how to import excell data to gridview so any helpful links will be very helpful. Thank you very much

export value

Upvotes: 0

Views: 883

Answers (2)

user12301067
user12301067

Reputation:

You can use the Microsoft.Office.Interop.Excel library Below is an example:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;

namespace Office
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Excel.Application excelApp = new Excel.Application();
        excelApp.Visible = false;

        var excelBook = excelApp.Workbooks.Open(@"C:\excelFile.xls");
        var excelSheet = (Excel.Worksheet)excelBook.Sheets[1];
        var lastrowR = excelSheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell).Row;
        var lastrowC = excelSheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell).Column;

        for (int i = 1; i <= lastrowC; i++)
        {
            dataGridView1.Columns.Add("Column"+i.ToString(), i.ToString());
        }

        for (int j = 1; j <= lastrowR; j++)
        {
            dataGridView1.Rows.Add();
        }

        for (int x=2; x <= 6; x++)
        {
            for (int y = 15; y <= 16; y++)
            {
                dataGridView1.Rows[y-14].Cells[x-1].Value = excelSheet.Cells[y, x].Value.ToString();
            }
        }

        excelBook.Close();
        excelApp.Quit();
    }
}
}

open the Excel file and take the desired cells and drop them into the desired cells in datagridview

Upvotes: 1

Marwen Jaffel
Marwen Jaffel

Reputation: 822

using OleDbConnection , OleDbDataAdapter , DataSet to do that :

  • Import System.Data.
  • Using ADO.NET to read content (SQL SELECT command like).
  • The content will be in DataSet
  • dataGridView1.DataSource = datatSet.Tables[0];

check this link to get the code Read and Import Excel File into DataSet

Upvotes: 0

Related Questions