【发布时间】:2017-04-04 04:55:49
【问题描述】:
嗨,我有以下字段名称的 excel 文件,mobileNo,TotalCoupen。我想将这些字段导入具有唯一序列号的 datagridview。如果一个人总共有 5 个 coupen,它将显示 5 个 coupen 序列,如 (10001,10002,10003 ,10004,10005) 我还附上了图片
这是我的代码 此代码成功加载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;
}
}
}
【问题讨论】:
-
您可能需要展示您试图吸引答案的内容,请参阅How to create a Minimal, Complete, and Verifiable example 另请参阅How do I ask a good question?
-
网格中的列名是否与 excel 字段匹配?
-
好的,但是我如何在每一行中添加 coupen 编号,如上图所示
标签: c# excel vb.net datagridview