I have Excel files that are in 2000 & 2003 format. I need to import them via C# code into an access DB. I have written a method to read the file into a data table. No matter which connection string i use (I have checked the other posts on this topic) I continue to get "Table is not in the correct format" error. Can someone please explain to me what I am doing wrong.
public static DataSet ParseExcel(string excelFile)
{
string sheetName = Path.GetFileNameWithoutExtension(excelFile);
string excelQuery = #"SELECT * FROM [" + sheetName + "]";
string excelConnctionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + "" + excelFile + "" +
#";Extended Properties=" + "" + #"Excel 8.0;HDR=Yes;" + "";
if(File.Exists(excelFile))
{
var myConnection = new OleDbConnection(excelConnctionString);
myConnection.Open();
var myCommand = new OleDbDataAdapter(excelQuery, excelConnctionString);
myCommand.TableMappings.Add("Table", "TestTable");
var dtSet = new DataSet();
myCommand.Fill(dtSet);
myConnection.Close();
return dtSet;
}
return null;
}
Go through this code example carefully and try to understand the work flow. You will get it real easy to write any kind programs for accessing excel data according to your requirements.
1.Here I just have a Upload Field in order to select the Excel File in .aspx file
<asp:FileUpload ID="Upload_File" runat="server" />
<asp:Button ID="Upload_Button" runat="server" Text="Upload" onclick="btnUpload_Click"/>
<asp:GridView ID="Gridview_Name" runat="server">
</asp:GridView>
Now lets see what happens in code behind file (.aspx.cs file)
protected void Upload_Button_Click(object sender, EventArgs e)
{
string connectionString = "";
if (Upload_File.HasFile) // checking whether file is selected to be uploaded
{
//getting name of the file
string fileName = Path.GetFileName(Upload_File.PostedFile.FileName);
//getting extension of the file (for checking purpose - which type .xls or .xlsx)
string fileExtension = Path.GetExtension(Upload_File.PostedFile.FileName);
string fileLocation = Server.MapPath("" + fileName); //exact location of the excel files
Upload_File.SaveAs(fileLocation);
//Check whether file extension is xls or xslx
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\"";
}
//Create OleDB Connection and OleDb Command
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);
con.Close();
Gridview_Name.DataSource = dtExcelRecords;
GridView_Name.DataBind();
}
else
{
Response.Write("Please Select a File to extract data ");
}
}
Step by Step Explanation :
We get the file name, extension, location .
And check it is the type (.xls or .xlsx - particularly for excels of 2003 or other formats).
Set connection strings according to the previous step.
Open oledb connection
Create the necessary data adapter and data table
open the connection
store the current table( where the data from excel is stored) in a datatable instance
Store the name of the sheet in astring by getting it from the current table
Fill the data adapter object(dAdapter) with the our data table (dtExcelRecords)
close the connection
Set datasource for the grid as out data table.
Bind it with our grid.
...And We are done!
Hope it helps.
Try this
OLEDB;Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\MyExcel.xls;Extended Properties="Excel 8.0;HDR=Yes;IMEX=1";
Related
I have a requirement to import the excel file in ASP.NET MVC. The importing is working as needed, there are 78 columns in the excel file. all the columns are imported except the last column.
How could I retrive last column from the excel file?
string conString = string.Empty;
if (getFileExtension.ToLower() == ".xls")
{
conString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + getFileName + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\""; ;
}
else if (getFileExtension.ToLower() == ".xlsx")
{
conString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + getFileName + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
}
OleDbConnection con = new OleDbConnection(conString);
if (con.State == ConnectionState.Closed) con.Open();
DataTable ExcelSheets = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
string SpreadSheetName = ExcelSheets.Rows[0]["TABLE_NAME"].ToString();
string query = "SELECT * FROM [" + SpreadSheetName + "]";
OleDbCommand cmd = new OleDbCommand(query, con);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
da.Dispose();
con.Close();
con.Dispose();
According to Import from excel to datatable skipping last column values, this may be an Excel or OleDb bug.
As a workaround, you might consider modifying the Excel sheet so as to add an additional column header at the end, with no data in the column. Then, the column that is skipped during import will be the one you don't need.
I have set a password on my excel sheet. To unlock the worksheet, I modified my OLEDB connection string, but it didn't work. I got an error that "the source contains no dataRows", which means that it couldn't read the data from the excel file.
Before it was fine. What might be my problem?
This is my code:
public DataTable getExcelData(string fileName, string sheetName, ComboBox[] User_ComboBox)
{
this.m_comboBox = User_ComboBox;
// connectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + fileName + "';Extended Properties= 'Excel 12.0 XML;HDR=No;IMEX=1'";
connectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Password=xyz;Extended Properties='Excel 8.0;HDR=YES'";
string errorMessage = "";
DataTable dt = new DataTable();
try
{
string query = "SELECT * FROM [" + sheetName + "]";
OleDbConnection con = new OleDbConnection(connectionString);
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, con);
dataAdapter.Fill(dt);
}
catch (Exception exp)
{
// errorCode = ErrorDefinition.ERROR_OLEDBERROR;
errorMessage = exp.Message;
}
return dt;
}
Instead of using an OleDbConnection you might consider using an Excel reading library like EPPlus to read the excel file. EPPlus supports reading password protected excel files.
You would need to implement some code to build the actual DataTable, but that should be simple enough. Just google it if you need to.
I am trying to select the "Report Details" worksheet from my excel file. However, I am having trouble selecting it,
The Microsoft Jet database engine could not find the object 'Report Details'. Make sure the object exists and that you spell its name and the path name correctly.
if (fileExtension == ".xls")
{
connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
}
else if (fileExtension == ".xlsx")
{
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
}
OleDbConnection con = new OleDbConnection(connString);
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);
cmd.CommandText = "SELECT * FROM [Report Details]"; //ERROR HERE
dAdapter.SelectCommand = cmd;
dAdapter.Fill(dtExcelRecords);
con.Close();
GridView1.DataSource = dtExcelRecords;
GridView1.DataBind();
Viewing my "Tables" in the dataset viewer, the connection string is able to access the file. The Report Details column is displayed as 'Report Details$'. I have tried entering it that way, but I am still getting an error.
Your question title says EXCEL/C# Cant Find Worksheet
Your post says I am trying to select the "Report Details" WORKSHEET from my excel file.
The error you are getting is
The Microsoft Jet database engine could not find the object 'Report Details'. Make sure the object exists and that you spell its name and the path name correctly.
Solution
You are missing a $ sign
Try this (TRIED AND TESTED)
cmd.CommandText = "SELECT * FROM [Report Details$]";
I was able to get the tabel name throuh dtExcelSheetName
cmd.CommandText = "SELECT * FROM [" + con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null).Rows[1][2].ToString() + "]";
It is working now.
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 am trying to find the best way of selecting an excel spreadsheet (xls and xlsx) using a fileupload control and then parsing it with filestream object and then populating a dataset.
This is my code so far which does the job but how it differs is I am saving the excel spreadsheet to a folder in my solution then querying the data using Microsoft ACE OLEDB connection.
protected void btnUpload_Click(object sender, EventArgs e)
{
string connectingString = "";
if (ctrlFileUpload.HasFile)
{
string fileName =
Path.GetFileName(ctrlFileUpload.PostedFile.FileName);
string fileExtension =
Path.GetExtension(ctrlFileUpload.PostedFile.FileName);
//Path.GetExtension(ctrlFileUpload.PostedFile.ContentType);
string fileLocation =
Server.MapPath("~/App_Data/" + fileName);
ctrlFileUpload.SaveAs(fileLocation);
// Check whether file extension is xls or xslx
if (fileExtension == ".xls")
{
connectingString =
"Provider=Microsoft.ACE.OLEDB.4.0;Data Source=" +
fileLocation + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=2\"";
}
else if (fileExtension == ".xlsx")
{
connectingString =
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
fileLocation + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=2\"";
}
// Create OleDb Connection and OleD Command
using (OleDbConnection con = new OleDbConnection(connectingString))
{
try
{
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
OleDbDataAdapter dAdapter = new OleDbDataAdapter(cmd);
//DataTable dtExcelRecords = new DataTable();
DataSet ds = new DataSet();
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);
dAdapter.Fill(ds);
//GridView1.DataSource = dtExcelRecords;
//GridView1.DataBind();
}
catch (Exception ex)
{
}
}
}
}
So to summarise I want to read the data in a spreadsheet and then bind it to a dataset but without saving the file to a physical path.
Is there a cleaner way of writing this code that I am missing. Thanks!!
I think it not possible to get data without save file to your server
If you can't save uploded file how can you give Data Source to your oleDbConnection string ??
you can delete file after finish this execution if you don't want to keep the file.
you can also refer this way https://stackoverflow.com/a/12420416/284240