首先我要读取这个excel文件然后生成Datable
用winform编程的方式
前台界面:
后台的代码
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using System.Data.OleDb;namespace 读Excel文件{ public partial class Form1 : Form { public Form1() { InitializeComponent(); } ////// 选择文件按钮 /// /// /// private void button1_Click(object sender, EventArgs e) { if (this.openFileDialog1.ShowDialog() == DialogResult.OK) { this.textBox1.Text = this.openFileDialog1.FileName; } } ////// 点击导出excel按钮 /// /// /// private void button2_Click(object sender, EventArgs e) { string File = this.openFileDialog1.FileName; DataTable dt = ExcelUp(File); dataGridView1.AutoGenerateColumns = false; dataGridView1.DataSource = dt; } ////// 读取指定excel表中的内容返回datatable /// /// 文件地址 ///表中内容 public DataTable ExcelUp(string fileName) { string filePath = fileName;//读取excel文件路径; DataTable dt = GetDataTable("Sheet1", filePath); return dt; } ////// 读取excel指定页中的内容 /// /// 页名 /// excel路径 ///protected DataTable GetDataTable(string strSheetName, string strExcelFileName) { //源的定义 string strConn = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source={0};" + "Extended Properties='Excel 8.0;HDR=NO;IMEX=1';", strExcelFileName); //Sql语句 string strExcel = string.Format("select * from [{0}$]", strSheetName); //定义存放的数据表 DataSet ds = new DataSet(); //连接数据源 OleDbConnection conn = new OleDbConnection(strConn); try { conn.Open(); //适配到数据源 OleDbDataAdapter adapter = new OleDbDataAdapter(strExcel, strConn); adapter.Fill(ds, strSheetName); } catch (Exception e) { throw e; } finally { conn.Close(); } return ds.Tables[strSheetName]; } }}
实现的效果:(说明:在excel中读取的datable中列头都是F几,如F1,F2等,要自己转换)