C# import excel filesheet to sql database error - c#

I have met the error: Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done. I'm using SQL Server 2005 and Visual Studio 2005.
I met this error during the import of an excel filesheet to a table in my sql table. Below is my code:
#region Using directives
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.IO;
using System.Configuration;
#endregion Using directives
namespace CSASPNETExcelImportExport
{
public partial class ExcelImport : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
// Get the row counts in SQL Server table.
protected int GetRowCounts()
{
int iRowCount = 0;
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Data Source=<IP>;Initial Catalog=SOD;Persist Security Info=True;User ID=<username>;Password=<password>"].ToString()))
{
SqlCommand cmd = new SqlCommand("select count(*) from <database>", conn);
conn.Open();
// Execute the SqlCommand and get the row counts.
iRowCount = (int)cmd.ExecuteScalar();
}
return iRowCount;
}
// Retrieve data from the Excel spreadsheet.
protected DataTable RetrieveData(string strConn)
{
DataTable dtExcel = new DataTable();
using (OleDbConnection conn = new OleDbConnection(strConn))
{
// Initialize an OleDbDataAdapter object.
OleDbDataAdapter da = new OleDbDataAdapter("select * from <database>", conn);
// Fill the DataTable with data from the Excel spreadsheet.
da.Fill(dtExcel);
}
return dtExcel;
}
// Import the data from DataTable to SQL Server via SqlBulkCopy
protected void SqlBulkCopyImport(DataTable dtExcel)
{
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Data Source=<ip>;Initial Catalog=SOD;Persist Security Info=True;User ID=<username>;Password=<password>"].ToString()))
{
// Open the connection.
conn.Open();
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(conn))
{
// Specify the destination table name.
bulkCopy.DestinationTableName = "<database>";
foreach (DataColumn dc in dtExcel.Columns)
{
// Because the number of the test Excel columns is not
// equal to the number of table columns, we need to map
// columns.
bulkCopy.ColumnMappings.Add(dc.ColumnName, dc.ColumnName);
}
// Write from the source to the destination.
bulkCopy.WriteToServer(dtExcel);
}
}
}
protected void btnImport_Click(object sender, EventArgs e)
{
// Before attempting to import the file, verify
// that the FileUpload control contains a file.
if (fupExcel.HasFile)
{
// Get the name of the Excel spreadsheet to upload.
string strFileName = Server.HtmlEncode(fupExcel.FileName);
// Get the extension of the Excel spreadsheet.
string strExtension = Path.GetExtension(strFileName);
// Validate the file extension.
if (strExtension != ".xls" && strExtension != ".xlsx")
{
Response.Write("<script>alert('Please select a Excel spreadsheet to import!');</script>");
return;
}
// Generate the file name to save.
string strUploadFileName = "~/UploadFiles/" + DateTime.Now.ToString("yyyyMMddHHmmss") + strExtension;
// Save the Excel spreadsheet on server.
fupExcel.SaveAs(Server.MapPath(strUploadFileName));
// Generate the connection string for Excel file.
string strExcelConn = "";
// There is no column name In a Excel spreadsheet.
// So we specify "HDR=YES" in the connection string to use
// the values in the first row as column names.
if (strExtension == ".xls")
{
// Excel 97-2003
strExcelConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath(strUploadFileName) + ";Extended Properties=\"Excel 8.0;HDR=Yes;\"";
//if the above doesn't work, you may need to prefix OLEDB; to the string, e.g.
//strExcelConn = "OLEDB;Provider=Microsoft.Jet.OLEDB.4.0;Data Source=<URL>" + Server.MapPath(strUploadFileName) + ";Extended Properties=\"Excel 8.0;HDR=Yes;\"";
}
else
{
// Excel 2007
strExcelConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=<URL>" + Server.MapPath(strUploadFileName) + ";Extended Properties=\"Excel 12.0 Xml;HDR=YES\"";
}
DataTable dtExcel = RetrieveData(strExcelConn);
// Get the row counts before importing.
int iStartCount = GetRowCounts();
// Import the data.
SqlBulkCopyImport(dtExcel);
// Get the row counts after importing.
int iEndCount = GetRowCounts();
// Display the number of imported rows.
lblMessages.Text = Convert.ToString(iEndCount - iStartCount) + " rows were imported into Person table";
if (rblArchive.SelectedValue == "No")
{
// Remove the uploaded Excel spreadsheet from server.
File.Delete(Server.MapPath(strUploadFileName));
}
}
}
}
}
Is it because my connectionstring error?
I have changed my connection strings as of what Nathan suggested. Now I met the following error:
http://i.stack.imgur.com/nWyte.png
What error is it this time? D:

It looks like you actually have several things wrong with your connection strings. For one thing, Excel connection strings should not include an "Initial Catalog", and they should include a Data Source referring to the file, not a server.
Try this instead:
// There is no column name In a Excel spreadsheet.
// So we specify "HDR=YES" in the connection string to use
// the values in the first row as column names.
if (strExtension == ".xls")
{
// Excel 97-2003
strExcelConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath(strUploadFileName) + ";Extended Properties=\"Excel 8.0;HDR=Yes;\"";
//if the above doesn't work, you may need to prefix OLEDB; to the string, e.g.
//strExcelConn = "OLEDB;Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath(strUploadFileName) + ";Extended Properties=\"Excel 8.0;HDR=Yes;\"";
}
else
{
// Excel 2007
strExcelConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Server.MapPath(strUploadFileName) + ";Extended Properties=\"Excel 12.0 Xml;HDR=YES\"";
}
Fyi, http://connectionstrings.com is a good resource for these kind of things.

Try removing "Persist Security Info=True" from your connection strings.
http://support.microsoft.com/kb/269495

Related

Excel to DataGridView

Additional information: The Microsoft Office Access database engine could not find the object 'C:\Users\username\Documents\sampleData.xls'. Make sure the object exists and that you spell its name and the path name correctly.
The Error is highlighted at
theDataAdapter.Fill(spreadSheetData);
Here's the sample data I used (tried in .csv , .xls , .xlsx )
Name Age Status Children
Johnny 34 Married 3
Joey 21 Single 1
Michael 16 Dating 0
Smith 42 Divorced 4
Here's the code associated:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Data.OleDb;
namespace uploadExcelFile
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnImport_Click(object sender, EventArgs e)
{
var frmDialog = new System.Windows.Forms.OpenFileDialog();
if (frmDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string strFileName = frmDialog.FileName;
System.IO.FileInfo spreadSheetFile = new System.IO.FileInfo(strFileName);
scheduleGridView.DataSource = spreadSheetFile.ToString();
System.Diagnostics.Debug.WriteLine(frmDialog.FileName);
System.Diagnostics.Debug.WriteLine(frmDialog.SafeFileName);
String name = frmDialog.SafeFileName;
String constr = String.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES""", frmDialog.FileName);
OleDbConnection myConnection = new OleDbConnection(constr);
OleDbCommand onlineConnection = new OleDbCommand("SELECT * FROM [" + frmDialog.FileName + "]", myConnection);
myConnection.Open();
OleDbDataAdapter theDataAdapter = new OleDbDataAdapter(onlineConnection);
DataTable spreadSheetData = myConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
theDataAdapter.Fill(spreadSheetData);
scheduleGridView.DataSource = spreadSheetData;
}
}
}
}
scheduleGridView is the DataGridViews name, & btnImport is the name for the import Button.
I've installed 2007 Office System Driver: Data Connectivity Components; which gave me the AccessDatabaseEngine.exe, but from there I've been stuck here without understanding how to get around this. It should go without saying that the filepath is correct in its entirety. There is no odd characters in the path name either (spaces, underlines, etc)
Mini Update :: (another dead end it seems like)
Although the initial error says, "could not find the object 'C:\Users\username\Documents\sampleData.xls'"
In the Debugger the exception is read as
When I look at details the exception as "C:\Users\username\Documents\sampleData.xls"
So I thought the error was that it wasn't taking the path as a literal, but this article C# verbatim string literal not working. Very Strange backslash always double
Shows very clearly that that is not my issue.
I am guessing you may be mistaken by what is returned from the following line of code…
DataTable spreadSheetData = myConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
The DataTable returned from this line will have nine (9) columns (TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, TABLE_TYPE, TABLE_GUID, DESCRIPTION, TABLE_PROPID, DATE_CREATED and DATE_MODIFIED). This ONE (1) DataTable returned simply “Describes” the worksheet(s) and named range(s) in the entire selected Excel workbook. Each row in this DataTable represent either a worksheet OR a named range. To distinguish worksheets from named ranges, the “TABLE_NAME” column in this DataTable has the name of the worksheet or range AND ends each “Worksheet” Name with a dollar sign ($). If the “TABLE_NAME” value in a row does NOT end in dollar sign, then it is a range and not a worksheet.
Therefore, when the line
OleDbDataAdapter theDataAdapter = new OleDbDataAdapter(onlineConnection);
Blows up and says it cannot file the “filename” error… is somewhat expected because this line is looking for a “worksheet” name, not a filename. On the line creating the select command…
OleDbCommand onlineConnection = new OleDbCommand("SELECT * FROM [" + frmDialog.FileName + "]", myConnection);
This is incorrect; you have already selected the filename and open the file with
String constr = String.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES""", frmDialog.FileName);
OleDbConnection myConnection = new OleDbConnection(constr);
myConnection.Open();
The correct OleDbCommand line should be…
OleDbCommand onlineConnection = new OleDbCommand("SELECT * FROM [" + sheetName + "]", myConnection);
The problem here is that the current code is not getting the worksheet names. Therefore, we cannot “select” the worksheet from the workbook then fill the adapter with the worksheet.
The other issue is setting the DataGridView’s DataSource to spreadSheetData… when you get the worksheet(s) from an Excel “Workbook”, you must assume there will be more than one sheet. Therefore a DataSet will work as a container to hold all the worksheets in the workbook. Each DataTable in the DataSet would be a single worksheet and it can be surmised that the DataGridView can only display ONE (1) of these tables at a time. Given this, below are the changes described along with an added button to display the “Next” worksheet in the DataGridView since there may be more than one worksheet in the workbook. Hope this makes sense.
int sheetIndex = 0;
DataSet ds = new DataSet();
public Form1() {
InitializeComponent();
}
private void btnImport_Click(object sender, EventArgs e) {
var frmDialog = new System.Windows.Forms.OpenFileDialog();
if (frmDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
String constr = String.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES""", frmDialog.FileName);
OleDbConnection myConnection = new OleDbConnection(constr);
myConnection.Open();
DataTable spreadSheetData = myConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string sheetName = "";
DataTable dt;
OleDbCommand onlineConnection;
OleDbDataAdapter theDataAdapter;
// fill the "DataSet" each table in the set is a worksheet in the Excel file
foreach (DataRow dr in spreadSheetData.Rows) {
sheetName = dr["TABLE_NAME"].ToString();
sheetName = sheetName.Replace("'", "");
if (sheetName.EndsWith("$")) {
onlineConnection = new OleDbCommand("SELECT * FROM [" + sheetName + "]", myConnection);
theDataAdapter = new OleDbDataAdapter(onlineConnection);
dt = new DataTable();
dt.TableName = sheetName;
theDataAdapter.Fill(dt);
ds.Tables.Add(dt);
}
}
myConnection.Close();
scheduleGridView.DataSource = ds.Tables[0];
setLabel();
}
}
private void setLabel() {
label1.Text = "Showing worksheet " + sheetIndex + " Named: " + ds.Tables[sheetIndex].TableName + " out of a total of " + ds.Tables.Count + " worksheets";
}
private void btnNextSheet_Click(object sender, EventArgs e) {
if (sheetIndex == ds.Tables.Count - 1)
sheetIndex = 0;
else
sheetIndex++;
scheduleGridView.DataSource = ds.Tables[sheetIndex];
setLabel();
}
I solved it. Well there was a workaround. I used the Excel Data Reader found in this thread: How to Convert DataSet to DataTable
Which led me to https://github.com/ExcelDataReader/ExcelDataReader
^ The readme was fantastic, just went to solution explorer, right click on references, manage NuGet Packages, select browse in the new box, enter ExcelDataReader, then in the .cs file be sure to include, "using Excel;" at the top, the code mentioned in the first link was essentially enough, but here's my exact code for those wondering.
var frmDialog = new System.Windows.Forms.OpenFileDialog();
if (frmDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
/*string strFileName = frmDialog.FileName;
//System.IO.FileInfo spreadSheetFile = new System.IO.FileInfo(strFileName);
System.IO.StreamReader reader = new System.IO.StreamReader(strFileName);
*/
string strFileName = frmDialog.FileName;
FileStream stream = File.Open(strFileName, FileMode.Open, FileAccess.Read);
//1. Reading from a binary Excel file ('97-2003 format; *.xls)
IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
//...
//2. Reading from a OpenXml Excel file (2007 format; *.xlsx)
//IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
//...
//3. DataSet - The result of each spreadsheet will be created in the result.Tables
//DataSet result = excelReader.AsDataSet();
//...
//4. DataSet - Create column names from first row
excelReader.IsFirstRowAsColumnNames = true;
DataSet result = excelReader.AsDataSet();
DataTable data = result.Tables[0];
//5. Data Reader methods
while (excelReader.Read())
{
//excelReader.GetInt32(0);
}
scheduleGridView.DataSource = data;
excelReader.Close();

Some Excel Files not moving from Shared Path to SQL Server

We have an application where the data in Excel file (present in shared path) moves to Database. In case of any error, the files moves to error folder by writing the error in a log file.It uses a windows service for the operation.
Sometimes the file doesn't have any error still moves to error folder by writing log External table is not in the expected format. But the same file uploading again for once or multiple times, its moving to Database without any errors.
The windows service, DB and shared path are present in XP Server. Application was running fine all these years. But in the recent days, above mentioned problem is occurring for almost every file.
We have installed Microsoft 2003, 2007,2012 office components and access engines too. But still the issue still persists.
I am mentioning the Windows service code below. Pls help. Thanks in advance.
using System.IO;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Data.Common;
namespace Impexp_Service
{
public partial class Service1 : ServiceBase
{
System.Timers.Timer T1 = new System.Timers.Timer();
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
///start
///
{
SqlConnection strconnection = new SqlConnection();
strconnection.ConnectionString = #"Data Source=XXXXXX;Initial Catalog=XXXX;User ID=XX;Password=XXXXXX;";
strconnection.Open();
// To get the all files placed at the shared path
DirectoryInfo directory = new DirectoryInfo(#"D:\Impexp\Data\");
FileInfo[] files = directory.GetFiles("*.xlsx");
foreach (var f in files)
{
string path = f.FullName;
// TO establish connection to the excel sheet
string excelConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=1\";";
//Create Connection to Excel work book
OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
excelConnection.Open();
//Create OleDbCommand to fetch data from Excel
OleDbCommand cmd = new OleDbCommand("Select * from [Report$]", excelConnection);
DbDataReader dr = cmd.ExecuteReader();
// OleDbDataReader dReader;
// dReader = cmd.ExecuteReader();
SqlBulkCopy sqlBulk = new SqlBulkCopy(strconnection);
//Give your Destination table name
sqlBulk.DestinationTableName = "imp_master_test";
sqlBulk.WriteToServer(dr);
excelConnection.Close();
File.Delete(path);
// To move error files to the error folder
/// end
T1.Interval = 20000;
T1.Enabled = true;
T1.Start();
T1.Elapsed += new System.Timers.ElapsedEventHandler(T1_Elapsed);
}
}
}
void T1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
T1.Enabled = false;
try
{
SqlConnection strconnection = new SqlConnection();
strconnection.ConnectionString = #"Data Source=10.91.XXXXXX;Initial Catalog=XXXXX;User ID=XXXXX;Password=XXXXX;";
strconnection.Open();
// To get the all files placed at the shared path
DirectoryInfo directory = new DirectoryInfo(#"D:\Impexp\Data\");
FileInfo[] files = directory.GetFiles("*.xlsx");
foreach (var f in files)
{
string path = f.FullName;
// TO establish connection to the excel sheet
string excelConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=1\";";
//Create Connection to Excel work book
OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
try
{
excelConnection.Open();
//Create OleDbCommand to fetch data from Excel
OleDbCommand cmd = new OleDbCommand("Select * from [Report$]", excelConnection);
DbDataReader dr = cmd.ExecuteReader();
// OleDbDataReader dReader;
// dReader = cmd.ExecuteReader();
SqlBulkCopy sqlBulk = new SqlBulkCopy(strconnection);
//Give your Destination table name
sqlBulk.DestinationTableName = "imp_master_prod";
sqlBulk.WriteToServer(dr);
excelConnection.Close();
File.Delete(path);
}
// To move error files to the error folder
catch (Exception exp)
{
excelConnection.Close();
File.Move(path, Path.Combine(#"D:\Impexp\error\", f.Name));
string path1 = #"D:\Impexp\error\error.txt";
if (File.Exists(path1))
{
// Create a file to write to.
using (StreamWriter sw = File.AppendText(path1))
{
sw.WriteLine("File : " + path + " : " + exp.Message);
sw.Flush();
}
}
T1.Enabled = true;
T1.Start();
}
}
strconnection.Close();
// End of TRY 1
}
catch (UnauthorizedAccessException UAEx)
{
string path1 = #"D:\Impexp\error\error.txt";
if (File.Exists(path1))
{
// Create a file to write to.
using (StreamWriter sw = File.AppendText(path1))
{
sw.WriteLine(UAEx.Message);
sw.Flush();
}
}
T1.Enabled = true;
T1.Start();
}
catch (PathTooLongException PathEx)
{
string path1 = #"D:\Impexp\error\error.txt";
if (File.Exists(path1))
{
// Create a file to write to.
using (StreamWriter sw = File.AppendText(path1))
{
sw.WriteLine(PathEx.Message);
sw.Flush();
}
}
T1.Enabled = true;
T1.Start();
}
T1.Enabled = true;
T1.Start();
}
protected override void OnStop()
{
}
}
}
I did some searching regarding the OLEDB coms and newer versions of Excel. It seems as though a great many people are having compatibility issues with them.
Unfortunately, it doesn't look like Microsoft is giving this any attention. Microsoft announced the depreciation of OLEDB functionality many years ago, and they have stopped adding any kind of internal support in their Office products and SQL servers. In fact,
The official shutdown date for MSAccess Web Apps and Web Databases was April 2018. That being the case, an update to the server, the client version of windows, or the client version of Excel may have triggered this, and it doesn't look like there is going to be a fix. I myself have started using 3rd party packages (free ones are available) to handle the interop with office products because I was tired of banging my head against the wall to create workarounds. Honestly, I don't know why Access still exists if they are taking away the ability to programmatically connect to an Access database.
I know this doesn't fix your problem, but it's better to face the truth and move on than to try to fix something that isn't going to fix.
Looking at this question, this appears to be an issue with reading the excel file, not the SQL table. Try changing the Excel connection string.
string excelConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=1\";";
to
string excelConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;HDR=Yes;IMEX=1\";
Also, looking at another answer, the root cause could be uploading newer versions of excel.
Are you using an Excel 2007 file with a connection string that uses: Microsoft.Jet.OLEDB.4.0 and Extended Properties=Excel 8.0?
You can change the string to some other as below:
public static string path = #"C:\src\RedirectApplication\RedirectApplication\301s.xlsx";
public static string connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;";
OR
Change the connection string from the link below:
http://www.connectionstrings.com/excel-2007

How to read excel (.xlsm) file, that file is using finansu add-in through C#

I have a excel (.xlsm) file with stock markets live data update through the excel add-in "finansu".
When I try to read excel data through the C# application in stock name column it shows the proper stock name but at the value column it does not show any thing. That stock value column is updated live values through the finansu add-in.
Please help me out to read these values as well.
Thanks in advance.
Below is the source code:
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=1\";";
query = "SELECT * FROM [RealTime$]";
conn = new OleDbConnection(connString);
if (conn.State == ConnectionState.Closed)
conn.Open();
cmd = new OleDbCommand(query, conn);
da = new OleDbDataAdapter(cmd);
dt = new System.Data.DataTable();
da.Fill(dt);
OLEDB won't be able to retrieve the data you want. I'm not familiar with the finansu add-in, but Excel Interop should be able to get what you need.
Microsoft.Office.Interop.Excel
Sample code:
using Microsoft.Office.Interop.Excel;
using System;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
var filename = #"C:\temp\Book1.xlsx";
var excel = new Microsoft.Office.Interop.Excel.Application();
var wb = excel.Workbooks.Open(filename);
Worksheet realtime = wb.Sheets["RealTime"];
foreach (Range row in realtime.UsedRange.Rows)
{
Console.WriteLine("{0}", row.Cells[1, 1].Value); // Column A
Console.WriteLine("{0}", row.Cells[1, 2].Value); // Column B
// etc ...
}
wb.Close(SaveChanges: false);
}
}
}

The Microsoft Office Access database engine could not find an object

I'm trying to copy data from excel to sql server but facing the following error.
The Microsoft Office Access database engine could not find the object 'sheet1$'. Make sure the object exists and that you spell its name and the path name correctly.
My code is:
protected void importdatafromexcel(string filepath)
{
string sqltable = "PFDummyExcel";
string exceldataquery = "select EmployeeId,EmployeeName,Amount from [Sheet1$]";
string excelconnectionstring = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepath + ";Extended Properties=Excel 12.0;Persist Security Info=False";
string sqlconnectionstring = System.Configuration.ConfigurationManager.ConnectionStrings["HRGold"].ConnectionString;
SqlConnection con = new SqlConnection(sqlconnectionstring);
OleDbConnection oledb = new OleDbConnection(excelconnectionstring);
OleDbCommand oledbcmd = new OleDbCommand(exceldataquery, oledb);
oledb.Open();
OleDbDataReader dr = oledbcmd.ExecuteReader();
SqlBulkCopy bulkcopy = new SqlBulkCopy(sqlconnectionstring);
bulkcopy.DestinationTableName = sqltable;
while (dr.Read())
{
bulkcopy.WriteToServer(dr);
}
oledb.Close();
}
Please tell me how i solve this..
This error is raised because of you are trying to access sheet (which name is sheet1) in excel file. By default first sheet name is "sheet1" but user have either rename this name or delete this sheet.
To resolved this issue first of all you have to get all sheet name from excel file, then you have to pass this sheet name in your above code to import data.
string filePath = "your file path";
string excelconnectionstring = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepath + ";Extended Properties=Excel 12.0;Persist Security Info=False";
OleDbConnection Connection = new OleDbConnection(excelconnectionstring);
DataTable activityDataTable = Connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if(activityDataTable != null)
{
//validate worksheet name.
var itemsOfWorksheet = new List<SelectListItem>();
string worksheetName;
for (int cnt = 0; cnt < activityDataTable.Rows.Count; cnt++)
{
worksheetName = activityDataTable.Rows[cnt]["TABLE_NAME"].ToString();
if (worksheetName.Contains('\''))
{
worksheetName = worksheetName.Replace('\'', ' ').Trim();
}
if (worksheetName.Trim().EndsWith("$"))
itemsOfWorksheet.Add(new SelectListItem { Text = worksheetName.TrimEnd('$'), Value = worksheetName });
}
}
// itemsOfWorksheet : all worksheet name is added in this
so you can use itemsOfWorksheet[0] as sheet name in-place of "sheet1"
I had similar issue, I sorted it out by
Saving the excel file from fileuploader to a temporary folder inside website folder.
Using path to that file in my connection string
Rest all was same and now the error: The Microsoft Office Access database engine could not find the object 'sheet1$' was gone.

How can I read the rows of an Excel csv or xls file into an ASP.NET app from a remote location using C#?

Here's my situation. I'm designing a program that takes Excel files (which may be in csv, xls, or xlsx format) from a remote network drive, processes the data, then outputs and stores the results of that process. The program provides a listbox of filenames that are obtained from the remote network drive folder using the method detailed in the accepted answer here. Once the user selects a filename from the listbox, I want the program to find the file and obtain the information from it to do the data processing. I have tried using this method to read the data from the Excel file while in a threaded security context, but that method just fails without giving any kind of error. It seems to not terminate. Am I going about this the wrong way?
Edit - (Final Notes: I have taken out the OleDbDataAdapter and replaced it with EPPlus handling.)
I was able to scrub sensitive data from the code, so here it is:
protected void GetFile(object principalObj)
{
if (principalObj == null)
{
throw new ArgumentNullException("principalObj");
}
IPrincipal principal = (IPrincipal)principalObj;
Thread.CurrentPrincipal = principal;
WindowsIdentity identity = principal.Identity as WindowsIdentity;
WindowsImpersonationContext impersonationContext = null;
if (identity != null)
{
impersonationContext = identity.Impersonate();
}
try
{
string fileName = string.Format("{0}\\" + Files.SelectedValue, #"RemoteDirectoryHere");
string connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.14.0; data source={0}; Extended Properties=Excel 14.0;", fileName);
OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM Sheet1", connectionString);
DataSet ds = new DataSet();
adapter.Fill(ds, "Sheet1");
dataTable = ds.Tables["Sheet1"];
}
finally
{
if (impersonationContext != null)
{
impersonationContext.Undo();
}
}
}
Additional Edit
Now xlsx files have been added to the mix.
Third Party
Third party solutions are not acceptable in this case (unless they allow unrestricted commercial use).
Attempts - (Final Notes: Ultimately I had to abandon OleDb connections.)
I have tried all of the different connection strings offered, and I have tried them with just one file type at a time. None of the connection strings worked with any of the file types.
Permissions
The User does have access to the file and its directory.
Your connection string might be the issue here. As far as I know, there isn't 1 that can read all xls, csv, and xlsx. I think you're using the XLSX connection string.
When I read xls, i use the following connection string:
#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + sFilePath + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1;'"
Having said that, I recommend using a 3rd party file reader/parser to read XLS and CSV since, from my experience, OleDbDataAdapter is wonky depending on the types of data that's being read (and how mixed they are within each column).
For XLS, try NPOI https://code.google.com/p/npoi/
For CSV, try http://www.codeproject.com/Articles/9258/A-Fast-CSV-Reader
For XLSX, try EPPlus http://epplus.codeplex.com/
I've had great success with the above libraries.
Is it really important that you use an OleDb interface for this? I've always done it with Microsoft.Office.Excel.Interop, to wit:
using System;
using Microsoft.Office.Interop.Excel;
namespace StackOverflowExample
{
class Program
{
static void Main(string[] args)
{
var app = new Application();
var wkbk = app.Workbooks.Open(#"c:\data\foo.xls") as Workbook;
var wksht = wkbk.Sheets[1] as Worksheet; // not zero-based!
for (int row = 1; row <= 100; row++) // not zero-based!
{
Console.WriteLine("This is row #" + row.ToString());
for (int col = 1; col <= 100; col++)
{
Console.WriteLine("This is col #" + col.ToString());
var cell = wksht.Cells[row][col] as Range;
if (cell != null)
{
object val = cell.Value;
if (val != null)
{
Console.WriteLine("The value of the cell is " + val.ToString());
}
}
}
}
}
}
}
As you will be dealing with xlsx extension, you should rather opt for the new connection string.
public static string getConnectionString(string fileName, bool HDRValue, bool WriteExcel)
{
string hdrValue = HDRValue ? "YES" : "NO";
string writeExcel = WriteExcel ? string.Empty : "IMEX=1";
return "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + fileName + ";" + "Extended Properties=\"Excel 12.0 xml;HDR=" + hdrValue + ";" + writeExcel + "\"";
}
Above is the code for getting the connection string. First argument expects the actual path for file location. Second argument will decide whether to consider first row values as column headers or not. Third argument helps decide whether you want to open the connection to create and write the data or simply read the data. To read the data set it to "FALSE"
public static ReadData(string filePath, string sheetName, List<string> fieldsToRead, int startPoint, int endPoint)
{
DataTable dt = new DataTable();
try
{
string ConnectionString = ProcessFile.getConnectionString(filePath, false, false);
using (OleDbConnection cn = new OleDbConnection(ConnectionString))
{
cn.Open();
DataTable dbSchema = cn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dbSchema == null || dbSchema.Rows.Count < 1)
{
throw new Exception("Error: Could not determine the name of the first worksheet.");
}
StringBuilder sb = new StringBuilder();
sb.Append("SELECT *");
sb.Append(" FROM [" + sheetName + fieldsToRead[0].ToUpper() + startPoint + ":" + fieldsToRead[1].ToUpper() + endPoint + "] ");
OleDbDataAdapter da = new OleDbDataAdapter(sb.ToString(), cn);
dt = new DataTable(sheetName);
da.Fill(dt);
if (dt.Rows.Count > 0)
{
foreach (DataRow row in dt.Rows)
{
string i = row[0].ToString();
}
}
cn.Dispose();
return fileDatas;
}
}
catch (Exception)
{
}
}
This is for reading 2007 Excel into dataset
DataSet ds = new DataSet();
try
{
string myConnStr = "";
myConnStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=MyDataSource;Extended Properties=\"Excel 12.0;HDR=YES\"";
OleDbConnection myConn = new OleDbConnection(myConnStr);
OleDbCommand cmd = new OleDbCommand("select * from [Sheet1$] ", myConn);
OleDbDataAdapter adapter = new OleDbDataAdapter();
adapter.SelectCommand = cmd;
myConn.Open();
adapter.Fill(ds);
myConn.Close();
}
catch
{ }
return ds;

Categories