Import Excel file to Datagridview in C# or VB.Net

user757321

hi i have excel file with following fields name,mobileNo,TotalCoupen.i want to import these field in datagridview with unique serial no.if a person have total 5 coupen it will show 5 coupen serial like (10001,10002,10003,10004,10005) i also attach image enter image description here

enter image description here

here is my code this code load excel file successfuly but not generate coupen no it only import excel file

 using System;
 using System.Collections.Generic;
 using System.ComponentModel;
 using System.Data;
 using System.Linq;
 using System.Text;
 using System.Windows.Forms;
 using System.IO;
 using System.Data.SqlClient;
 using System.Configuration;
 using System.Data.OleDb;
 using Excel = Microsoft.Office.Interop.Excel;

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

    private void Form1_Load(object sender, EventArgs e)
    {
        dataGridView1.Visible = false;
    }

    private void btnChoose_Click(object sender, EventArgs e)
    {
        string filePath = string.Empty;
        string fileExt = string.Empty;
        OpenFileDialog file = new OpenFileDialog();//open dialog to choose file
        if (file.ShowDialog() == System.Windows.Forms.DialogResult.OK)//if there is a file choosen by the user
        {
            filePath = file.FileName;//get the path of the file
            fileExt = Path.GetExtension(filePath);//get the file extension
            if (fileExt.CompareTo(".xls") == 0 || fileExt.CompareTo(".xlsx") == 0)
            {
                try
                {
                    DataTable dtExcel = new DataTable();
                    dtExcel = ReadExcel(filePath, fileExt);//read excel file
                    dataGridView1.Visible = true;
                    dataGridView1.DataSource = dtExcel;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message.ToString());
                }
            }
            else
            {
                MessageBox.Show("Please choose .xls or .xlsx file only.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Error);//custom messageBox to show error
            }
        }
    }

    private void btnClose_Click(object sender, EventArgs e)
    {
        this.Close();//to close the window(Form1)
    }

    public DataTable ReadExcel(string fileName, string fileExt)
    {
        string conn = string.Empty;
        DataTable dtexcel = new DataTable();
        if (fileExt.CompareTo(".xls") == 0)//compare the extension of the file
            conn = @"provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + ";Extended Properties='Excel 8.0;HRD=Yes;IMEX=1';";//for below excel 2007
        else
            conn = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1';";//for above excel 2007
        using (OleDbConnection con = new OleDbConnection(conn))
        {
            try
            {
                OleDbDataAdapter oleAdpt = new OleDbDataAdapter("select * from [Sheet1$]", con);//here we read data from sheet1
                oleAdpt.Fill(dtexcel);//fill excel data into dataTable
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
        }
        return dtexcel;
    }
}

}

JohnG

I am not sure why you would want to add these IMHO duplicate rows. A simple solution is to create a new DataTable with the extra rows. Loop through all the rows in the excel data table then loop total coupen times for each new row then update coupen no as the picture shows. Again I am not sure why you would do this but here is one way. The code below makes a new DataTable from the DataTable returned from ReadExcel method. The AddDuplicates methods add the rows as per the requirement.

dtExcel = ReadExcel(filePath, fileExt);//read excel file
DataTable dgvTable = AddDuplicates(dtExcel);
dataGridView1.Visible = true;
//dataGridView1.DataSource = dtExcel;
dataGridView1.DataSource = dgvTable;

private DataTable AddDuplicates(DataTable dt) {
  DataTable dtcopy = dt.Clone();
  int curCount = 100000;
  double coupenCount = 0;
  foreach(DataRow dr in dt.Rows) {
    coupenCount = (double)dr.ItemArray[2];
    for (int i = 0; i < coupenCount; i++) {
      dtcopy.Rows.Add(dr.ItemArray[0], dr.ItemArray[1], ++curCount);
    }
  }
  return dtcopy;
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

import csv file into datagridview with specific column and row in vb.net

From Dev

vb.net load excel data in datagridview miss date value

From Dev

Exporting data from DataGridView as Excel table using VB.NET

From Dev

Exported excel file from datagridview shows error when opened VB

From Dev

VB.net Find And Replace from Data in a DataGridView in a text file

From Dev

How to export the content of a datagridview to a text file vb.net 2010

From Dev

C# DataGridView to Excel File errors

From Dev

C# + VB: Import reg file

From Dev

Import specific data from excel to datagrid vb.net

From Dev

Import specific data from excel to datagrid vb.net

From Dev

I can't import "row ids" XML nodes into DataGridView in VB.net

From Dev

Import VB.NET DLL into C#.Net Project

From Dev

I cant import excel to datagridview

From Dev

vb.net calculation in datagridview

From Dev

Uploading excel file to DataGridView

From Dev

How to include/import a c++ app in VB.net

From Dev

prompt for opening a save dialog for excel file using vb.net

From Dev

Issue with Excel file after exporting using VB.net

From Dev

from DataGridView saving to text file issue when saving date values on vb.net

From Dev

How to export the exact values of the datagridview into excel VB

From Dev

export datagridview header column to excel vb 2012

From Dev

Import data from excel into DataGridview with specific condition

From Dev

Delete a row in DataGridView Control in VB.NET

From Dev

vb.net datagridview not showing selected row

From Dev

Drag and Drop in datagridview in vb.net

From Dev

Set selectedindex for comboboxcell in datagridview vb.net

From Dev

Duplicate values in a datagridview using vb.net

From Dev

Stopping blank cells in a datagridview - VB.NET

From Dev

VB.Net binding datagridview Comboboxcolumn to datagridviewTextboxColumn

Related Related

  1. 1

    import csv file into datagridview with specific column and row in vb.net

  2. 2

    vb.net load excel data in datagridview miss date value

  3. 3

    Exporting data from DataGridView as Excel table using VB.NET

  4. 4

    Exported excel file from datagridview shows error when opened VB

  5. 5

    VB.net Find And Replace from Data in a DataGridView in a text file

  6. 6

    How to export the content of a datagridview to a text file vb.net 2010

  7. 7

    C# DataGridView to Excel File errors

  8. 8

    C# + VB: Import reg file

  9. 9

    Import specific data from excel to datagrid vb.net

  10. 10

    Import specific data from excel to datagrid vb.net

  11. 11

    I can't import "row ids" XML nodes into DataGridView in VB.net

  12. 12

    Import VB.NET DLL into C#.Net Project

  13. 13

    I cant import excel to datagridview

  14. 14

    vb.net calculation in datagridview

  15. 15

    Uploading excel file to DataGridView

  16. 16

    How to include/import a c++ app in VB.net

  17. 17

    prompt for opening a save dialog for excel file using vb.net

  18. 18

    Issue with Excel file after exporting using VB.net

  19. 19

    from DataGridView saving to text file issue when saving date values on vb.net

  20. 20

    How to export the exact values of the datagridview into excel VB

  21. 21

    export datagridview header column to excel vb 2012

  22. 22

    Import data from excel into DataGridview with specific condition

  23. 23

    Delete a row in DataGridView Control in VB.NET

  24. 24

    vb.net datagridview not showing selected row

  25. 25

    Drag and Drop in datagridview in vb.net

  26. 26

    Set selectedindex for comboboxcell in datagridview vb.net

  27. 27

    Duplicate values in a datagridview using vb.net

  28. 28

    Stopping blank cells in a datagridview - VB.NET

  29. 29

    VB.Net binding datagridview Comboboxcolumn to datagridviewTextboxColumn

HotTag

Archive