private void buttonDaoRu_Click(object sender, EventArgs e) //导入按钮事件
{
//申明打开对话框
OpenFileDialog dlg = new OpenFileDialog();
//默然文件后缀
dlg.DefaultExt = "xls ";
//文件后缀列表
dlg.Filter = "EXCEL文件(*.XLS)|*.xls ";
//默然路径是系统当前路径
dlg.InitialDirectory = Directory.GetCurrentDirectory();
//打开对话框
dlg.ShowDialog();
if (dlg.FileName != "")
{
DataSet ds = Common.Common.ExcelToDS(dlg.FileName);
GC.Collect(); //垃圾回收
//操作dataset,得到你想要的
}
}
//需要添加引用
//using Excel=Microsoft.Office.Interop.Excel;
//using System.Reflection;
//using System.Data.OleDb;
/// <summary>
/// 读取Excel文档
/// </summary>
/// <param name="Path">文件名称</param>
/// <returns>返回一个数据集</returns>
public static DataSet ExcelToDS(string filename)
{
string fileNameString = filename;
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + fileNameString + "';Extended Properties=/"Excel 8.0;HDR=YES;IMEX=1;/"";
OleDbConnection conn = new OleDbConnection(strConn);
DataSet ds = null;
conn.Open();
string strExcel = "";
OleDbDataAdapter myCommand = null;
strExcel = "select * from [Sheet1$]";
myCommand = new OleDbDataAdapter(strExcel, strConn);
ds = new DataSet();
myCommand.Fill(ds);
conn.Close();
return ds;
}
大体上就是这个样子!我做的时候,在导入按钮那卡壳了,找不到一个思路。
现在好了,希望对刚工作的朋友得以借鉴!
这也是我第一次发博客!^ ^