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

前提是你 提交于 2020-05-16 12:31:34

问题


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

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

}


回答1:


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



回答2:


Try doing it this way.

using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;

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

        private void button1_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);
            dataGridView1.DataSource = DtSet.Tables[0];
            MyConnection.Close();
        }
    }
}


来源:https://stackoverflow.com/questions/43198566/import-excel-file-to-datagridview-in-c-sharp-or-vb-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!