try
{
string connectionString = string.Empty;
if (Path.GetExtension(fileName) == ".xlsx")
{
connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName +
";Extended Properties=Excel 12.0;";
}
else
{
Debug.Print(connectionString);
connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Path.Combine(Server.MapPath("~/Content"), fileName) + ";Extended Properties=Excel 8.0;";
//connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Path.Combine(Server.MapPath("~/Content"), fileName) + ";Extended Properties=\"Excel 12.0 Xml;HDR=YES\"";
}
OleDbCommand selectCommand = new OleDbCommand();
OleDbConnection connection = new OleDbConnection();
OleDbDataAdapter adapter = new OleDbDataAdapter();
connection.ConnectionString = connectionString;
if (connection.State != ConnectionState.Open)
connection.Open();
//connection.Get
DataTable dtSchema = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
}
catch (Exception ex)
{
Debug.Print(ex.ToString());
}
connection.Open() seems to be connecting just fine. Now I have gotten a dtSchema Data Table object. I am needing to get the name of the Excel worksheet or worksheets that were gotten if any. I am also scanning the object to find out where the column names are. There is supposed to be some columns in the schema. Is it documented where the columns are?
When I do some output in my immediate window:
dtSchema.Columns[0].ToString()
"TABLE_CATALOG"
dtSchema.Columns[1].ToString()
"TABLE_SCHEMA"
dtSchema.Columns[2].ToString()
"TABLE_NAME"
dtSchema.Columns[3].ToString()
"TABLE_TYPE"
These are not the column names of the first worksheet, which is what I am looking for mainly the name of the first worksheet and its columns.
Thank you for posting..
If you want to look for column names. See the resultant COLUMN_NAME column
DataTable dtCols = this.connection.GetSchema("Columns");
TABLE_NAME is also helpful for your case to identify the Sheet.
Related
I wanna read data from excel spreadsheet and insert them into Access data base(.accdb). there is a problem with data format in excel. some cells are in incorrect type. Correct format for example is 99999 and incorrect is 9999-888 . because of dash(-) ole data adapter return null values instead of text. how should i get whole cell block?
I have tried change the cell format of excel from General to Text but the problem is still available.
thanks
string connectionStringExcel = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + openFileDialog1.FileName + ";Extended Properties=Excel 12.0;";
using (OleDbConnection connectionExcel = new OleDbConnection(connectionStringExcel))
{
OleDbDataAdapter daExcel = new OleDbDataAdapter(#"SELECT * FROM [priclist$]", connectionExcel);
DataTable dtExcel = new DataTable();
daExcel.Fill(dtExcel);
dataGridView1.DataSource = dtExcel;
}
By default, the Microsoft.ACE.OLEDB.12.0 provider tries to determine variable type for each column, and assumes the majority type is the column type.
You can override this behaviour by specifying IMEX=1 in the connection string, which uses text when encountering mixed-field types instead of setting the ones not matching the type to Null. Then you can handle the values in your C# code:
string connectionStringExcel = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + openFileDialog1.FileName + ";Extended Properties=Excel 12.0;IMEX=1;";
Read more about the IMEX property by following the link in the comment below
I use the following code to transfer data from Excel to datagrid :
private void btnreadExcell_MouseDown(object sender, MouseButtonEventArgs e)
{
try
{
string filePath = string.Empty;
string fileExt = string.Empty;
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Excel Files|*.xls;*.xlsx;*.xlsm";
Nullable<bool> result = ofd.ShowDialog();
if (result == true)//if there is a file choosen by the user
{
filePath = ofd.FileName;//get the path of the file
try
{
DataTable dtExcel = new DataTable();
dtExcel = ReadExcel(filePath, fileExt);//read excel file
// dataGrid.Visible = true;
dataGrid.ItemsSource = dtExcel.DefaultView;
datagridheader();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
con.Close();
}
catch { MessageBox.Show("error");}
}
public DataTable ReadExcel(string fileName, string fileExt)
{
DataTable dtexcel = new DataTable();
try
{
string conn = string.Empty;
if (fileExt.CompareTo(".xls") == 0)//compare the extension of the file
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;HDR=Yes;IMEX=1';";//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)
{
MessageBox.Show(ex.Message.ToString());
}
}
conn.Clone();
}
catch { MessageBox.Show("error"); }
return dtexcel;
}
My error has been Solved!!! with set both IMEX=1 And HDR=No. if you have changed your header in excel files(first row) use below code to solve same problem as i asked above.
try this
(two connection string have same meaning)
string connectionStringExcel = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + openFileDialog1.FileName + ";Extended Properties='Excel 12.0;HDR=No;IMEX=1';"
Or
string connectionStringExcel = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +"T13970524.xlsx" + ";Extended Properties=\"Excel 12.0 Xml;HDR=No;IMEX=1\";";
I am developing a program to import excel spreadsheets with C # language, using the OLEDB component, when importing a spreadsheet with 100547 rows the program can only read 54046.
Follows the source code:
public class ReadExcel
{
public string ConnectionExcel(ExcelUpload excelUpload)
{
//connection String for xls file format.
if (excelUpload.fileExtension == ".xls")
{
excelUpload.excelConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + excelUpload.fileLocation + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
}
//connection String for xlsx file format.
else if (excelUpload.fileExtension == ".xlsx")
{
excelUpload.excelConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excelUpload.fileLocation + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
}else
{
excelUpload.excelConnectionString = "";
}
return excelUpload.excelConnectionString;
}
public DataTable readArqExcel(string excelConnectionString, DataSet ds)
{
//Create Connection to Excel work book and add oledb namespace
OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
excelConnection.Open();
DataTable dt = new DataTable();
dt = excelConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
return null;
}
//Numero de planilhas contidas no excel
String[] excelSheets = new String[dt.Rows.Count];
int count = 0;
//excel data saves in temp file here.
foreach (DataRow row in dt.Rows)
{
excelSheets[count] = row["TABLE_NAME"].ToString();
count++;
}
OleDbConnection excelConnection1 = new OleDbConnection(excelConnectionString);
string query = string.Format("Select * from [{0}]", excelSheets[0]);
using (OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, excelConnection1))
{
dataAdapter.Fill(ds);
}
excelConnection.Close();
return ds.Tables[0];
}
I have tested IIS 8 (REMOTE SERVER) and IIS Express (Visual Studio local server), I noticed that on the IIS Express server the code works perfectly, but in IIS 8 the code ends up reading the file in half.
Is it some kind of web server configuration?
problem resolved, i altered string of connection OLEBD with MsExcel.
Alter parameter IMEX = 2 for IMEX = 1, as below
if (excelUpload.fileExtension == ".xls")
{
excelUpload.excelConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + excelUpload.fileLocation + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\"";
}
//connection String for xlsx file format.
else if (excelUpload.fileExtension == ".xlsx")
{
excelUpload.excelConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excelUpload.fileLocation + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=1\"";
}
I have an excel file and an oledb connection to it. When reading data while file is opened in windows, it throws the following error (at Adapter.Fill method).
However, the code runs fine when file is not opened manually.
private System.Data.DataSet GetExcelData()
{
// Create new DataSet to hold information from the worksheet.
System.Data.DataSet objDataset1 = new System.Data.DataSet();
DataTable dt = new DataTable();
try
{
string path = ConfigurationManager.AppSettings["ExcelFilePath"];
//string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;";
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1;\"";
OleDbConnection objConn = new OleDbConnection(connectionString);
objConn.Open();
//String strConString = "SELECT * FROM [Data Version5.2$A2:ZZ] where [Status] = 'aa'";//Status
String strConString = "SELECT * FROM [Data Version5.2$A2:ZZ] where [Status] IS NULL OR [Status]='SubReport'";//Status SubReport
OleDbCommand objCmdSelect = new OleDbCommand(strConString, objConn);
OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();
// Pass the Select command to the adapter.
objAdapter1.SelectCommand = objCmdSelect;
// Fill the DataSet with the information from the work sheet.
objAdapter1.Fill(objDataset1, "ExcelData");
objConn.Close();
}
catch (Exception ex)
{
throw ex;
}
return objDataset1;
}
The error message is
Assuming you don't need to write to the file, try adjusting your connection string to include the read only mode (Mode=Read). I have that in all of mine (where I don't need to write to the file) and I've never had a problem reading from workbooks that are already open:
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
path + ";Mode=Read;Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1;\"";
I also don't tend to read Excel files as XML, so the Extended Properties for my connection strings are Excel 12.0;HDR=YES;IMEX=1;
I am importing data from MS Excel.
The code i have written is,
var ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" +
uploadfile.PostedFile.FileName + ";" + "Extended Properties=Excel 12.0;";
OleDbConnection objConn = new OleDbConnection(sConnectionString);
objConn.Open();
try
{
var objCmdSelect = new OleDbCommand("select * from [Sheet1$]", objConn);
}
and so on.
I got an error which looks very generic to me
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 worksheet name is spelled correclty
but for my confirmation, i did below code
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if(dt == null)
{
return null;
}
var excelSheets = new String[dt.Rows.Count];
int i = 0;
// Add the sheet name to the string array.
foreach(DataRow row in dt.Rows)
{
excelSheets[i] = row["TABLE_NAME"].ToString();
i++;
}
*
but i got my Data Table null.
My question is the connection is open successfully but i can't read data from the excel file.
Is there any special Authentication required.?
because i am getting the above error.
Instead if Ace.OLEDB you may try by Microsoft.Jet.OLEDB, because I faced the simillar then I switch over to Jet.OLEDB
string MyExelFile = "C:\Temp\Sample.xls";
string MyExcelSheet = "[Sheet1$]";
string StrConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + MyExelFile + ";
Extended Properties=\"Excel 8.0; HDR=Yes; IMEX=1\"";
String MySQLSelect = "select * from " + MyExcelSheet + "";
DataTable Items=new DataTable() ;
System.Data.OleDb.OleDbConnection Cn = new System.Data.OleDb.OleDbConnection();
Cn.ConnectionString = StrConn;
System.Data.OleDb.OleDbDataAdapter Da = new System.Data.OleDb.OleDbDataAdapter
(MySQLSelect, Cn);
Cn.Open();
Da.Fill(Items);
Cn.Close();
</pre>
I wrote this method to update an excel cell:
public void update(string fileName, string sheetName)
{
string connString = connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Server.MapPath(fileName) + ";Extended Properties=Excel 12.0";
try
{
OleDbConnection oledbConn = new OleDbConnection(connString);
oledbConn.Open();
OleDbCommand cmd = new OleDbCommand("UPDATE ["+sheetName+"$B5:B5] SET F1=17", oledbConn);
cmd.ExecuteNonQuery();
oledbConn.Close();
}
catch(Exception ex)
{
Debug.Write("Error: " + ex.Message);
}
}
I called it like this:
update("test.xls", "test");
The B5 cell is available in "test" sheet, but the value never gets updated.
I even tried with this one:
UPDATE ["+sheetName+"$B5:B5] SET F1='17'
and I always got this exception: No value given for one or more required parameters.
Any idea?
Thanks in advance.
EDIT I notice you have missed HDR=No.
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FileName +
";Extended Properties=""Excel 12.0;HDR=No"""
EDIT
Tested in C# Express
Either:
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=z:\\docs\\myspreadsheet.xls;Extended Properties='Excel 12.0 xml;HDR=No'"
Note xml
Or
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=z:\\docs\\myspreadsheet.xls;Extended Properties='Excel 8.0;HDR=No'"
For *.xls