winform打开excel

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp6
{

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

private void button1_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog fd = new OpenFileDialog();
fd.Filter = "(*.xls,*.xlsx)|*.xls;*.xlsx";
fd.Title = "打开文件夹";
string path = "";
fd.InitialDirectory = "C:\\Users\\LG\\Desktop\\";//对话框的初始目录
fd.FilterIndex = 1;//用于取得或设置当前选择的文件过滤项的索引值

if (fd.ShowDialog() == DialogResult.OK)//确认按下确定键
{
path = fd.FileName;//获取文件名(包含路径)
}

string tableName = Form1_Programs.GetExcelFirstTableName(path);//使用获取表头函数
string TSql = "SELECT * FROM [" + tableName + "]";//查询
//获取读取数据
DataTable table = Form1_Programs.ExcelToDataSet(path, TSql).Tables[0];
dataGridView1.DataSource = table;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}

 

 

 

 

Form1_Programs部分

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WindowsFormsApp6
{
class Form1_Programs
{
public static string GetExcelFirstTableName(string fullPath)
{
string tableName = null;

//判断是否存在
if (File.Exists(fullPath))
{
using (OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.Ace.OleDb.12.0;" + "data source=" + fullPath + @";Extended Properties='Excel 12.0; HDR=YES; IMEX=1'"))
{
//开启读取
conn.Open();

//获取名
tableName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null).Rows[0][2].ToString().Trim();

//释放读取资源
conn.Dispose();

//关闭读取
conn.Close();
}
}
return tableName;
}

public static DataSet ExcelToDataSet(string filename, string sql)
{
//读取文件连接
string strCon = @"Provider=Microsoft.Ace.OleDb.12.0;" + "data source=" + filename + @";Extended Properties='Excel 12.0; HDR=YES; IMEX=1'";

//字符串初始化
System.Data.OleDb.OleDbConnection myConn = new System.Data.OleDb.OleDbConnection(strCon);

//开启读取
myConn.Open();

//更新获取数据资源连接
System.Data.OleDb.OleDbDataAdapter myCommand = new System.Data.OleDb.OleDbDataAdapter(sql, myConn);

//实例数据集
DataSet ds = new DataSet();

//填充数据集
myCommand.Fill(ds);

//释放读取资源
myConn.Dispose();

//关闭连接
myConn.Close();

//释放读取资源
myConn.Close();

return ds;
}
}
}

posted @ 2021-07-02 14:00  Lee597  阅读(422)  评论(0)    收藏  举报