I am reading excel sheet using below code but that gives blank data table.
public static DataTable ReadExcel(string fileName)
{
string fileExt = ".xlsx";
string conn = string.Empty;
DataTable dtexcel = new DataTable();
if (fileExt.CompareTo(".xlsx") == 0)
conn = #"provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + ";Extended Properties='Excel 8.0;HRD=Yes;IMEX=1';"; //for below excel 2007
else
conn = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties='Excel 12.0 Xml;HDR=YES';"; //for above excel 2007
using (OleDbConnection con = new OleDbConnection(conn))
{
try
{
OleDbDataAdapter oleAdpt = new OleDbDataAdapter("select * from [Sheet1$]", con); //here we read data from sheet1
oleAdpt.Fill(dtexcel); //fill excel data into dataTable
}
catch(Exception ex) { }
}
return dtexcel;
}
It displays empty data table as below screenshot.
you forgot few things, like OleDbConnection.Open(); and using OleDbCommand
public DataTable ReadExcel(string fileName)
{
string fileExt = ".xlsx";
string sheetName = "Sheet1$";
string conn = string.Empty;
DataTable dt = new DataTable();
if (fileExt.CompareTo(".xlsx") != 0)
conn = #"provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + ";Extended Properties='Excel 8.0;HRD=Yes;IMEX=1';"; //for below excel 2007
else
conn = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties='Excel 12.0 Xml;HDR=YES';"; //for above excel 2007
using (OleDbConnection con = new OleDbConnection(conn))
using ( OleDbCommand cmd = new OleDbCommand())
{
con.Open();
try
{
cmd.Connection = con;
cmd.CommandText = "SELECT * FROM [" + sheetName + "]";
dt.TableName = sheetName;
using (OleDbDataAdapter da = new OleDbDataAdapter(cmd))
{
da.Fill(dt);
}
}
catch (Exception ex) { }
}
return dt;
}
try rhis code hope it help you
protected void btn_Click(object sender, EventArgs e)
{
string filename = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName);
FileUpload1.SaveAs(Server.MapPath("File/" + filename));
string CurrentFilePath = Server.MapPath("File/" + filename);
string connectString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + CurrentFilePath + ";Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1;\"";
OleDbConnection conn = new OleDbConnection(connectString);
conn.Open();
DataTable Sheets = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
foreach (DataRow dr in Sheets.Rows)
{
string sht = dr[2].ToString().Replace("'", "");
OleDbDataAdapter da = new OleDbDataAdapter("Select * From [" + sht + "]", conn);
DataTable dt = new DataTable();
da.Fill(dt);
}
}
For me working following code
string filePath = AppDomain.CurrentDomain.BaseDirectory.Replace("\\bin\\Debug", "").Replace("\\bin\\Release", "");
string fileLocation = filePath + ConfigurationManager.AppSettings["EmployeeDetailsFilePath"];
Stream inputStream = File.Open(fileLocation, FileMode.Open, FileAccess.Read);
IExcelDataReader reader = ExcelReaderFactory.CreateOpenXmlReader(inputStream);
reader.IsFirstRowAsColumnNames = true;
DataSet dataSet = reader.AsDataSet();
inputStream.Dispose();
reader.Dispose();
here must add reference of ExcelDataReader dll in your project.
Related
My code below gives me the following error as i typed in the title
What am I doing wrong here?
OpenFileDialog openFileDialog1 = new OpenFileDialog();
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string huru = openFileDialog1.FileName;
this.textBox1.Text = huru;
string pathConn;
OleDbConnection conn;
DataTable spreadSheetData;
string sheetName = "";
OleDbCommand onlineConnection;
OleDbDataAdapter myDataAdapter;
DataTable dt = new DataTable();
if (huru.Substring(huru.Length - 3) == "lsx")
{
pathConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + huru
+ ";Extended Properties = \"Excel 12.0 Xml;HDR=YES\"; ";
}
else
{
pathConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source= " + huru
+ ";Extended Properties=\"Excel 8.0;HDR=yes;\";";
}
conn = new OleDbConnection(pathConn);
spreadSheetData = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
foreach (DataRow dr in spreadSheetData.Rows)
{
sheetName = dr["TABLE_NAME"].ToString();
sheetName = sheetName.Replace("'", "");
if (sheetName.EndsWith("$"))
{
onlineConnection = new OleDbCommand("SELECT * FROM [" + sheetName + "]", conn);
myDataAdapter = new OleDbDataAdapter(onlineConnection);
dt = new DataTable();
dt.TableName = sheetName;
myDataAdapter.Fill(dt);
ds.Tables.Add(dt);
}
}
}
spreadSheetData starts falling null
my codes refer to Excel to DataGridView
1st answered by JohnG
and this video https://www.youtube.com/watch?v=CfNMPDJVjPI
Thanks for any help!
Your code should be something like this:
I have encapsulated your connection inside a using, so we are sure freeing resources. Also it's necessary to open the connection.
OpenFileDialog openFileDialog1 = new OpenFileDialog();
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
//Prepare things
using(OleDbConnection conn = new OleDbConnection(pathConn))
{
conn.Open(); //Added this line
spreadSheetData = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
foreach (DataRow dr in spreadSheetData.Rows)
{
//Do staff
}
}
}
You must open your connection before using it :
conn = new OleDbConnection(pathConn);
conn.Open();
You should also use the "Using" statement to properly dispose the connection when not used anymore.
OpenFileDialog openFileDialog1 = new OpenFileDialog();
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string huru = openFileDialog1.FileName;
this.textBox1.Text = huru;
string pathConn;
//OleDbConnection conn;
DataTable spreadSheetData;
string sheetName = "";
OleDbCommand onlineConnection;
OleDbDataAdapter myDataAdapter;
DataTable dt = new DataTable();
if (huru.Substring(huru.Length - 3) == "lsx")
{
pathConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + huru
+ ";Extended Properties = \"Excel 12.0 Xml;HDR=YES\"; ";
}
else
{
pathConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source= " + huru
+ ";Extended Properties=\"Excel 8.0;HDR=yes;\";";
}
using(OleDbConnection conn = ew OleDbConnection(pathConn))
{
//conn = new OleDbConnection(pathConn);
conn.Open();
spreadSheetData = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
foreach (DataRow dr in spreadSheetData.Rows)
{
sheetName = dr["TABLE_NAME"].ToString();
sheetName = sheetName.Replace("'", "");
if (sheetName.EndsWith("$"))
{
onlineConnection = new OleDbCommand("SELECT * FROM [" + sheetName + "]", conn);
myDataAdapter = new OleDbDataAdapter(onlineConnection);
dt = new DataTable();
dt.TableName = sheetName;
myDataAdapter.Fill(dt);
ds.Tables.Add(dt);
}
}
}
}
I want to import data to gridview from Excel. And I have done using System.Data.OleDb as
if (ExlSheet.HasFile)
{
string fileName = Path.GetFileName(ExlSheet.PostedFile.FileName);
string fileExtension = Path.GetExtension(ExlSheet.PostedFile.FileName);
string fileLocation = Server.MapPath("~/App_Data/" + fileName);
ExlSheet.SaveAs(fileLocation);
if (fileExtension == ".xls")
{
connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
fileLocation + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
}
else if (fileExtension == ".xlsx")
{
connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
fileLocation + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
}
OleDbConnection con = new OleDbConnection(connectionString);
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = con;
OleDbDataAdapter dAdapter = new OleDbDataAdapter(cmd);
DataTable dtExcelRecords = new DataTable();
con.Open();
DataTable dtExcelSheetName = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string getExcelSheetName = dtExcelSheetName.Rows[0]["Table_Name"].ToString();
cmd.CommandText = "SELECT * FROM [" + getExcelSheetName + "]";
dAdapter.SelectCommand = cmd;
dAdapter.Fill(dtExcelRecords);
gv.DataSource = dtExcelRecords;
gv.DataBind();
}
How to achieve the same using LinqToExcel
Try this
if (ExlSheet.HasFile)
{
string fileName = Path.GetFileName(ExlSheet.PostedFile.FileName);
string fileExtension = Path.GetExtension(ExlSheet.PostedFile.FileName);
string fileLocation = Server.MapPath("~/App_Data/" + fileName);
ExlSheet.SaveAs(fileLocation);
ExcelQueryFactory excelFile = new ExcelQueryFactory(fileLocation);
var data = from a in excelFile.Worksheet("Sheet1") select a;
var columnNames = excelFile.GetColumnNames("Sheet1");
DataTable dtExcelRecords = new DataTable();
foreach (var columnName in columnNames)
{
dtExcelRecords.Columns.Add(columnName);
}
foreach (var row in data)
{
DataRow dr = dtExcelRecords.NewRow();
foreach (var columnName in columnNames)
{
dr[columnName] = row[columnName];
}
dtExcelRecords.Rows.Add(dr);
}
gv.DataSource = dtExcelRecords;
gv.DataBind();
}
I want to import excel file data in to SQL Server but this gives an error as shown below:
external table is not in the expected format xls
I am working on windows 8.1 OS and excel 2013. I am using the following code.
try
{
if (FlUploadcsv.HasFile)
{
string FileName = FlUploadcsv.FileName;
string filePath = "C:\\Users\\admin\\Desktop\\Sheet1.xlsx";
string path = filePath;// string.Concat(Server.MapPath("~/Document/" + FlUploadcsv.FileName));
FlUploadcsv.PostedFile.SaveAs(path);
OleDbConnection OleDbcon = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;");
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Sheet1$]", OleDbcon);
OleDbDataAdapter objAdapter1 = new OleDbDataAdapter(cmd);
ds = new DataSet();
objAdapter1.Fill(ds);
Dt = ds.Tables[0];
}
}
catch (Exception ex)
{
}
First you need to Replace Connection string :
OleDbConnection OleDbcon = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;");
With this :
If you are use import for .xls then use below one :
OleDbConnection OleDbcon = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + "; Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"");
If you are use import for .xlsx then use below one :
OleDbConnection OleDbcon = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + "; Extended Properties='Excel 12.0;HDR=YES;IMEX=1;';");
Try this blow one :
try
{
if (FlUploadcsv.HasFile)
{
OleDbConnection OleDbcon;
OleDbCommand cmd = new OleDbCommand(); ;
OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();
DataSet ds = new DataSet();
DataTable dtExcelData = new DataTable();
string FileName = FlUploadcsv.FileName;
string filePath = "C:\\Users\\admin\\Desktop\\Sheet1.xlsx";
string path = filePath;// string.Concat(Server.MapPath("~/Document/" + FlUploadcsv.FileName));
FlUploadcsv.PostedFile.SaveAs(path);
if (Path.GetExtension(path) == ".xls")
{
OleDbcon = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + "; Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"");
}
else if (Path.GetExtension(path) == ".xlsx")
{
OleDbcon = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + "; Extended Properties='Excel 12.0;HDR=YES;IMEX=1;';");
}
OleDbcon.Open();
cmd.Connection = OleDbcon;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM [Sheet1$]";
objAdapter1 = new OleDbDataAdapter(cmd);
objAdapter1.Fill(ds);
dtExcelData = ds.Tables[0];
string consString = "Your Sql Connection string";
/* You want insert into your sql database table using SqlBulkCopy. */
using (SqlConnection con = new SqlConnection(consString))
{
using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con))
{
//Set the database table name
sqlBulkCopy.DestinationTableName = "SqlDatabase Table name where you want insert data";
//[OPTIONAL]: Map the Excel columns with that of the database table
sqlBulkCopy.ColumnMappings.Add(".xls/.xlsx Header column name(Id)", "Your database table column(IndexId)");
.
.
.
con.Open();
sqlBulkCopy.WriteToServer(dtExcelData);
con.Close();
}
}
/* You want insert into your sql database table using SqlBulkCopy. */
}
}
catch (Exception ex)
{ }
Here is a similar way to do it:
string filename = System.IO.Path.GetFileName(FileUpload1.FileName);
if (FileUpload1.HasFile == true) {
string fp = System.IO.Path.GetDirectoryName(FileUpload1.FileName);
string full = "C:\\Users\\user\\Documents\\" + filename;
TextBox1.Text = full;
//FileUpload1.SaveAs(Server.MapPath("Files/" + filename))
try {
string connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=full;Extended Properties=Excel 8.0;HDR=YES;";
string cmdStr = "Select * from [Sheet1$]";
using (OleDbConnection oledbconn = new OleDbConnection(connStr)) {
using (OleDbCommand oledbcmd = new OleDbCommand(cmdStr, oledbconn)) {
oledbconn.Open();
OleDbDataAdapter oledbda = new OleDbDataAdapter(oledbcmd);
DataSet ds = new DataSet();
oledbda.Fill(ds);
//save to an SQL Database
oledbconn.Close();
}
}
} catch (Exception ex) {
TextBox2.Text = ex.ToString();
}
}
I want to import data from an Excel 2003 file, but my C# program gives error
External table is not in the expected format
I use this code:
string ExcelContentType = "application/vnd.ms-excel";
string Excel2010ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
if (fileuploadExcel.HasFile)
{
//Check the Content Type of the file
if (fileuploadExcel.PostedFile.ContentType == ExcelContentType || fileuploadExcel.PostedFile.ContentType == Excel2010ContentType)
{
try
{
//Save file path
string path = string.Concat(Server.MapPath("~/TempFiles/"), fileuploadExcel.FileName);
//Save File as Temp then you can delete it if you want
fileuploadExcel.SaveAs(path);
string excelConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\"";
// Create Connection to Excel Workbook
using (OleDbConnection connection = new OleDbConnection(excelConnectionString))
{
OleDbCommand command = new OleDbCommand("Select * FROM [Sheet1$]", connection);
connection.Open();
// Create DbDataReader to Data Worksheet
using (DbDataReader dr = command.ExecuteReader())
{
// SQL Server Connection String
string sqlConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString.ToString();
// Bulk Copy to SQL Server
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnectionString))
{
bulkCopy.DestinationTableName = "Excel_table";
bulkCopy.WriteToServer(dr);
lblMessage.Text = "The data has been exported succefuly from Excel to SQL";
}
}
}
}
catch (Exception ex)
{
lblMessage.Text = ex.Message;
}
}
}
Hi here i am using this to import from Excel File.Try this.Works 100%...
Here you should have a folder inside your application named as "Files" where after uploading your excel file,it will be stored and your program will read from the excel file available inside "Files" Folder.
protected void btnImport_Click(object sender, EventArgs e)
{
ArrayList alist = new ArrayList();
string connString = "";
string strFileType = Path.GetExtension(fileuploadExcel.FileName).ToLower();
string fileBasePath = Server.MapPath("~/Files/");
string fileName = Path.GetFileName(this.fileuploadExcel.FileName);
string fullFilePath = fileBasePath + fileName;
//Connection String to Excel Workbook
if (strFileType.Trim() == ".xls")
{
connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fullFilePath +
";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\"";
}
else if (strFileType.Trim() == ".xlsx")
{
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fullFilePath +
";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=1\"";
}
if (fileuploadExcel.HasFile)
{
string query = "SELECT [UserName],[Education],[Location] FROM [Sheet1$]";
using(OleDbConnection conn = new OleDbConnection(connString))
{
if (conn.State == ConnectionState.Closed)
conn.Open();
OleDbCommand cmd = new OleDbCommand(query, conn);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
Session["griddata"] = ds.Tables[0];
grvExcelData.DataSource = Session["griddata"];
grvExcelData.DataBind();
}
}
}
Try this: Connection String
string connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;";
You can use SSIS tool( Sql server integration services)
create connection to excel sheet then add source and destination
your source will be excel sheet and your destination will be Database table
ok?
if you need more info please tell me...
I would like to get the sheet name of the uploaded excel file using C# code. The file may be in .xls or .xlsx format. The Code I have used is as follows:
protected void btnGenerateCSV_Click(object sender, EventArgs e)
{
string sourceFile = ExcelFileUpload.PostedFile.FileName;
string worksheetName = ?? //(How to get the first sheetname of the uploaded file)
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + sourceFile + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\"";
if (sourceFile.Contains(".xlsx"))
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + sourceFile + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=1\"";
try
{
conn = new OleDbConnection(strConn);
conn.Open();
cmd = new OleDbCommand("SELECT * FROM [" + worksheetName + "$]", conn);
cmd.CommandType = CommandType.Text;
wrtr = new StreamWriter(targetFile);
da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
for (int x = 0; x < dt.Rows.Count; x++)
{
string rowString = "";
for (int y = 0; y < dt.Columns.Count; y++)
{
rowString += "\"" + dt.Rows[x][y].ToString() + "\",";
}
wrtr.WriteLine(rowString);
}
}
catch (Exception exp)
{
}
finally
{
if (conn.State == ConnectionState.Open)
conn.Close();
conn.Dispose();
cmd.Dispose();
da.Dispose();
wrtr.Close();
wrtr.Dispose();
}
}
(How to get the first sheetname of the uploaded file)
string worksheetName = ??
I use this to get sheet names from a .xlsx file and loop through all the names to read sheets one by one.
OleDbConnection connection = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filename + ";Extended Properties='Excel 12.0 xml;HDR=YES;'");
connection.Open();
DataTable Sheets = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
foreach(DataRow dr in Sheets.Rows)
{
string sht = dr[2].ToString().Replace("'", "");
OleDbDataAdapter dataAdapter = new OleDbDataAdapter("select * from [" + sht + "]", connection);
}
DataTable Sheets = oleConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
for(int i=0;i<Sheets.Rows.Count;i++)
{
string worksheets= Sheets.Rows[i]["TABLE_NAME"].ToString();
string sqlQuery = String.Format("SELECT * FROM [{0}]", worksheets);
}
If the Excel is too big, This code will waste a lot of time in(conn.open()). Use Openxml will be better(use less time),but if the Excel is Open---Using openxml to read will have the exception but oldbhelper wile have no exception. My english is pool , sorry.-----Chinese boy
I use Microsoft excel library Microsoft.Office.Interop.Excel. Then you can use index to get the worksheet name as following.
string path = #"C\Desktop\MyExcel.xlsx" //Path for excel
using Excel = Microsoft.Office.Interop.Excel;
xlAPP = new Excel.Application();
xlAPP.Visible = false;
xlWbk = xlAPP.Workbooks.Open(path);
string worksheetName = xlWbk.Worksheets.get_Item(1).Name //pass Index here. Reemember that index starts from 1.
xlAPP.Quit();
releaseObject(xlWbk);
releaseObject(xlAPP);
//Always handle unmanaged code.
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Unable to release the Object " + ex.ToString());
}
finally
{
GC.Collect();
}
}