Get Data Set from Excel via OleDbConnection - CSharp Office

CSharp examples for Office:Excel

Description

Get Data Set from Excel via OleDbConnection

Demo Code


using System.IO;//w  w w  .j ava  2  s.  co m
using System.Net;
using System.Data.OleDb;
using System.Data;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System;

public class Main{
        //string p = Directory.GetCurrentDirectory() + @"\????.xls";
//ds = ExcelHelper.GetDataSet(p, "select * from [Sheet1$]");
        public static DataSet GetDataSet(string path, string strCom)
        {
            //MessageBox.Show(path);
            try
            {
                string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + "; Extended Properties=Excel 8.0;";
                // MessageBox.Show(path);
                OleDbConnection myConn = new OleDbConnection(strCon);
                // MessageBox.Show(strCon);
                myConn.Open();

                OleDbDataAdapter myCommand = new OleDbDataAdapter(strCom, myConn);

                DataSet ds = new DataSet();

                myCommand.Fill(ds, "[Sheet1$]");

                myConn.Close();

                return ds;
            }
            catch (Exception e)
            {
                throw e;
            }
        }
}

Related Tutorials