Thursday 12 September 2013

Reading Excel File in C#

Reading Excel File in C#

Anyone can help me to correct my coding ? why is it I cant read my excel
file in C# ?
Did I miss anything ? need help !!! thanks in advance!
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.IO;
using System.Data.OleDb;
namespace ReadExcel
{
public partial class Form1 : Form
{
private DataTable ReadExcelFile(string Sheet1, string path)
{
using (OleDbConnection conn = new OleDbConnection())
{
DataTable dt = new DataTable();
string Sample = @"E:\Sample.xlsx";
string fileExtension = Path.GetExtension(Sample);
if (fileExtension == ".xls")
conn.ConnectionString =
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Sample +
";" + "Extended Properties='Excel 8.0;HDR=YES;'";
if (fileExtension == ".xlsx")
conn.ConnectionString =
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Sample
+ ";" + "Extended Properties='Excel 12.0 Xml;HDR=YES;'";
using (OleDbCommand comm = new OleDbCommand())
{
comm.CommandText = "Select * from [" +Sheet1 + "$]";
comm.Connection = conn;
using (OleDbDataAdapter da = new OleDbDataAdapter())
{
da.SelectCommand = comm;
da.Fill(dt);
return dt;
}
}
}
}

No comments:

Post a Comment