您好我有以下字段名稱,mobileNo,TotalCoupen.i excel文件想要在datagridview中導入這些字段與唯一的序列號如果一個人總共5 coupen它會顯示5 coupen串行像(10001,10002,10003,10004,10005)我還附上圖片將Excel文件導入到C#或VB.Net中的Datagridview
這裏是我的代碼 這段代碼加載Excel文件successfuly但不產生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;
}
}
}
你可能需要出示你試圖吸引一個答案看看[如何創建一個最小的,完整的,並且可驗證的示例](http://stackoverflow.com/help/mcve)也見[我如何問一個好問題?](http://stackoverflow.com/help/how-to-ask) – OSKM
在你的網格中匹配excel字段的列名? – ADyson
好的,但我如何在每一行中添加唯一的coupen數字像上面的圖像 – user757321