i'm currently using oledb for getting excel data to dataset/datatable in c#. so far it works but i encountered a problem in getting excel sheets. i have this code in getting the data from excel to dataset
bool ret = false;
DataSet dset = new DataSet();
string strConn;
try
{
if (filePath.Substring(filePath.LastIndexOf('.')).ToLower() == ".xlsx")
{
strConn = String.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0;HDR=NO;IMEX=1;""", filePath);
}
else
strConn = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties='Excel 8.0;HDR=NO;'";
//SELECT * FROM [{0}$A5:BE] dont accept all sheet names
string sql = String.Format("SELECT * FROM [{0}$A6:BH]", sheetname);
OleDbDataAdapter adap = new OleDbDataAdapter(sql, strConn);
adap.Fill(dset, "SignalList");
my problem is this select statement where i get the excel data. sometimes it accept this select statement:
String.Format("SELECT * FROM [{0}$A6:BH]", sheetname),
and sometimes it accepts this statement:
String.Format("SELECT * FROM [{0} $A6:BH]", sheetname)
Am i doing something wrong on getting data on excel? sorry for my english. please help
Related
I am using OleDB connection for importing .xltx and it is showing exception - "External table not in expected format"
System.Data.DataTable dtExcel = new System.Data.DataTable();
string filePath = #"C:\Template.xltx";
string xlConnStr = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + filePath + "';Extended Properties= 'Excel 12.0;HDR=Yes;IMEX=1;Format=xltx'";
System.Data.OleDb.OleDbConnection cxlConn = new OleDbConnection(xlConnStr);
string query = "Select * from [Sheet2$A3:C34]";
OleDbDataAdapter dtAdapter = new OleDbDataAdapter(query, cxlConn);
dtAdapter.Fill(dtExcel);
I am using Microsoft.Jet.OLEDB.12.0 and Extended Properties=Excel 12.0
Can anyone please help me?
If not Oledb, any other way to read .xltx into datatable?
dtExcel is datatable, the line at which exception thrown is dtAdapter.Fill(dtExcel);
Hi is it possible to read an excel file without headers using EPPLUS?
You can save the excel in csv format and skip the first line after reading all line.
var lines = File.ReadAllLines(FileName).Skip(1);
or you can use oledb connection to import data from excel to datatable .
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + filename + ";" + "Extended Properties='Excel 12.0;HDR=YES;IMEX=1;';";
string query = string.Format("SELECT * FROM [{0}$]", tablename);
using (OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, connectionString))
{
DataSet jobDataSet = new DataSet();
dataAdapter.Fill(jobDataSet, "jobInfo");
DataTable jobDataTable = jobDataSet.Tables["jobInfo"];
}
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 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";