将Excel文件导入C#或VB.Net中的Datagridview

时间:2017-04-04 04:55:50

标签: c# excel vb.net datagridview

嗨我有excel文件,其中包含以下字段名称,mobileNo,TotalCoupen.i想要在datagridview中导入这些字段,使用唯一的序列号。如果一个人总共有5个coupen,它将显示5个coupen序列号(10001,10002,10003) ,10004,10005)我还附上图片enter image description here

enter image description here

这是我的代码 这段代码成功加载了excel文件,但没有生成coupen,它只导入excel文件

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

}

2 个答案:

答案 0 :(得分:1)

我不确定您为什么要添加这些IMHO重复行。一个简单的解决方案是使用额外的行创建一个新的DataTable。循环遍历excel数据表中的所有行,然后为每个新行循环total coupen次,然后更新coupen no,如图所示。我不知道为什么你会这样做,但这是一种方式。以下代码从DataTable方法返回的DataTable中生成新的ReadExcelAddDuplicates方法根据要求添加行。

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

答案 1 :(得分:0)

尝试这样做。

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