I have Excel Data Like above. Whenever i trying to get the value as 12/1/2015. I used to get 1-Dec,2-Dec etc Like this image
bool hasHeaders = true;
string HDR = hasHeaders ? "Yes" : "No";
string strConn;
if (path.Substring(path.LastIndexOf('.')).ToLower() == ".xlsx")
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0 Xml; HDR =" + HDR + ";IMEX=1;TypeGuessRows=0;ImportMixedTypes=Text\"";
else
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=\"Excel 8.0;HDR=" + HDR + ";IMEX=1;TypeGuessRows=0;ImportMixedTypes=Text\"";
retrieving the data from Excel.
OleDbDataAdapter dataHeader = new OleDbDataAdapter("SELECT * FROM [" + sheet + Coords + "]", Connection);
dataHeader.Fill(tableHeader);
please find the mistake.
Related
I tried these two connection strings:
Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + this.m_SourceFileName + ";Extended Properties='Excel 12.0;HDR=No; IMEX=1;
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + this.m_SourceFileName + ";Extended Properties='Excel 8.0; HDR=No; IMEX=1;
I'm getting an exception
External table is not in the expected format
The same files are working after just open and close the file manually. Then tried to read the same code is working.
Kindly help to know the exact issue with Excel.
This is the code I tried:
this.m_ConnectionToExcelBook =
new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + this.m_SourceFileName + ";Extended Properties='Excel 12.0;HDR=Yes; IMEX=0;'");
try
{
this.m_ConnectionToExcelBook.Open();
}
catch
{
this.m_ConnectionToExcelBook =
new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + this.m_SourceFileName + ";Extended Properties='Excel 8.0; HDR=No; IMEX=1;'");
this.m_ConnectionToExcelBook.Open();
}
i am using OleDbConnection for connection string here but I am getting error at line
if (conn.State == ConnectionState.Closed)
Error as CS0019: Operator '==' cannot be applied to operands of type 'System.Data.ConnectionState' and 'ConnectionState'
here is my code
protected void btnSave_Click(object sender, EventArgs e)
{
DataTable dtExcel = new DataTable();
dtExcel.Clear();
string StrCount = String.Empty;
string connString = "";
HttpPostedFile File = FileUpload1.PostedFile;
string strFileType = Path.GetExtension(FileUpload1.FileName).ToLower();
string path = FileUpload1.PostedFile.FileName;
string Filename = path.Substring(path.LastIndexOf("\\") + 1, path.Length - path.LastIndexOf("\\") - 1);
path = Server.MapPath(#"~/Excels/" + "/" + Filename.ToString());
File.SaveAs(path);
if (strFileType.Trim() == ".xls")
{
connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
}
else if (strFileType.Trim() == ".xlsx")
{
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
}
string query = "SELECT * FROM [Sheet 1$]";
OleDbConnection conn = new OleDbConnection(connString);
conn.Close();
if (conn.State == ConnectionState.Closed)
conn.Open();
OleDbCommand cmd = new OleDbCommand(query, conn);
OleDbDataAdapter daExcel = new OleDbDataAdapter(cmd);
daExcel.Fill(dtExcel);
conn.Close();}
I dont know why?
I tried the solutions from other link but it didn't helped
It seems to me you have an ambiguous class or property name. ConnectionState appears to have two meanings.
Try to prefix ConnectionState as follows with its full namespace:
if (conn.State == System.Data.ConnectionState.Closed)
After reading your comments on Patrick's answer, I see else is missing here
if (strFileType.Trim() == ".xls")
{
connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
}
else if (strFileType.Trim() == ".xlsx")
{
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
}
May be connString is left blank as strFileType is not .xls.or .xlsx.
Good day!
I try to open and parse excel file into DataSet.
So, i use OleDbConnection:
if (_filePath.Substring(_filePath.LastIndexOf('.')).ToLower() == ".xlsx")
// strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
// + _filePath + ";Extended Properties=\"Excel 12.0;HDR=" + HDR + ";IMEX=0\"";
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
+ _filePath + ";Extended Properties=\"Excel 12.0 Xml;HDR=" + HDR + ";IMEX=1;TypeGuessRows=0;ImportMixedTypes=Text;\"";
// strConn="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + _filePath + ";Extended Properties=Excel 12.0;";
else
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + _filePath + ";Extended Properties=\"Excel 8.0;HDR=" + HDR + ";IMEX=1\"";
But some column are empty!
The next column parses well (it with same data).
Can you tell me how to fix it?
Then i fill Dataset:
OleDbConnection conn = new OleDbConnection(strConn);
System.Data.DataSet dtSet;
System.Data.OleDb.OleDbDataAdapter oleCommand;
oleCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [" + sheetName + "]", conn);
oleCommand.TableMappings.Add("Table", sheetName);
dtSet = new System.Data.DataSet();
oleCommand.Fill(dtSet);
oleCommand.Dispose();
conn.Close();
return dtSet.Tables[0];
But, some columns are empty!
May be, it happens because excel file has format:
Cell1--------------|Value1------------|
Cell2---|Cell3-----|Value2---|Value4--|
So, dataset fill columns :
Cell1---|-------|--Value1------|-----|
Cell2---|Cell3--|---Empty(!)---|Value4|
So, i need to get Empty(!) column.
About invalid data at column.
I copy and paste this column at right column- and it works!
But,i should use last format, not mine.
HDR="NO";
Maybe you ran into this error:
OleDB & mixed Excel datatypes : missing data
What's the value of 'HDR'? Take a look at the Datatypes of the Columns, maybe they are mixed.
I have code from a colleague, this code creates a few excel sheets with Epplus. With my code I would like to add an database extract 10k+/- lines. Because of the large amount of data it takes too long with Epplus, because you need to write each cell. With OleDB it only takes a few seconds. But I can't open a previously created excel by Epplus with OleDB. Even with different connection strings.
This my code works perfect if you separate the two code blocks.
var excelPath = "C:\\test_" + DateTime.Today.ToString("yyyyMMdd_") + DateTime.Now.ToString("hh") + DateTime.Now.Minute.ToString() + ".xlsx";
using (ExcelPackage xlPackage = new ExcelPackage(new FileInfo(excelPath)))
{
ExcelWorksheet worksheet = xlPackage.Workbook.Worksheets.Add("Schedule V");
worksheet.Cell(1, 1).Value = "test";
xlPackage.Save();
xlPackage.Dispose();
}
var strCn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excelPath + ";Extended Properties='Excel 12.0 Xml';";
using (OleDbConnection conn = new OleDbConnection(strCn))
{
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "CREATE TABLE [table1] (id INT, name VARCHAR, datecol DATE );";
cmd.ExecuteNonQuery();
cmd.CommandText = "INSERT INTO [table1](id,name,datecol) VALUES(1,'AAAA','2014-01-01');";
cmd.ExecuteNonQuery();
conn.Close();
}
I tried the following connection strings but they all give the same error:
OleDbException was unhandled, External table is not in the expected
format.
My diffrent connection string I tried:
var strCn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excelPath + ";Extended Properties='Excel 12.0';";
var strCn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excelPath + ";Extended Properties='Excel 12.0 Xml';";
var strCn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excelPath + ";Extended Properties='Excel 12.0 Xml;HDR=YES';";
var strCn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excelPath + ";Extended Properties='Excel 12.0 Xml;HDR=YES;IMEX=1';";
var strCn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excelPath + ";Extended Properties='Excel 8.0;HDR=YES';";
var strCn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + excelPath + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1';";
What am I doing wrong here?
I guess, it should be like this, rather than hardcoding you should use OleDbConnectionStringBuilder class
OleDbConnectionStringBuilder connectionStringBuilder = new OleDbConnectionStringBuilder();
connectionStringBuilder.Provider = "Microsoft.ACE.OLEDB.12.0";
connectionStringBuilder.DataSource = excelPath; // This is your Excel File Full Path
connectionStringBuilder.Add("Mode", "Read");
const string extendedProperties = "Excel 12.0;IMEX=1;HDR=YES";
connectionStringBuilder.Add("Extended Properties", extendedProperties);
String connectionString = connectionStringBuilder.ToString();
// Create connection object by using the preceding connection string.
using (var objConn = new OleDbConnection(connectionString))
{
// Open connection with the database.
objConn.Open();
// Do operations with your File here
}
I was getting this error consistently with .xlsx files created with EPPlus 4.0.4. I remembered this was working prior to upgrading to EPPlus 4.x. I downgraded to 3.1.3.3 and I no longer get this error.
i am using OLEDB server to read excel file in my ASP.NET MVC project. then i m getting error
"The Microsoft Jet database engine cannot open the file ''.It is already opened exclusively by another user, or you need permission to view its data". same code with different comnnection string of CSV file is work fine but For Excel connectionString i am getting this error. is there anyone know the solution for this please.
My code is:
public JsonResult ImportCSVFiles()
{
HttpPostedFileBase hpf = null;
foreach (string file in Request.Files)
{
hpf = Request.Files[file] as HttpPostedFileBase;
}
string[] FileName;
string filename = hpf.FileName;
string DestinationPath = Server.MapPath("..") + "\\CSVFiles\\";
if (!Directory.Exists(DestinationPath))
{
Directory.CreateDirectory(DestinationPath);
if (System.IO.File.Exists(Server.MapPath("..") + "\\CSVFiles\\" + filename) == false)
{
hpf.SaveAs(DestinationPath + filename);
}
else
{
System.IO.File.Delete(Server.MapPath("..") + "\\CSVFiles\\" + filename);
hpf.SaveAs(DestinationPath + filename);
}
}
else
{
if (System.IO.File.Exists(Server.MapPath("..") + "\\CSVFiles\\" + filename) == false)
{
hpf.SaveAs(DestinationPath + filename);
}
else
{
System.IO.File.Delete(Server.MapPath("..") + "\\CSVFiles\\" + filename);
hpf.SaveAs(DestinationPath + filename);
}
}
bool isFirstRowHeader = true;
string header = isFirstRowHeader ? "Yes" : "No";
string path = "";
string pathOnly = Path.GetDirectoryName(DestinationPath);
string fileName = Path.GetFileName(DestinationPath + "\\" + filename);
string sql = #"SELECT * FROM [" + fileName + "]";
//using (OleDbConnection connection = new OleDbConnection(
// #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathOnly +
// ";Extended Properties=\"Text;HDR=" + header + "\""))
using (OleDbConnection connection = new OleDbConnection(
#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathOnly +
";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\";"))
using (OleDbCommand command = new OleDbCommand(sql, connection))
using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
{
DataTable dataTable = new DataTable();
dataTable.Locale = CultureInfo.CurrentCulture;
adapter.Fill(dataTable);
}
}
commented connectionstring is for CSV file and CSV file works fine with same code.
I had the same problem with a program I was recently working on. My solution was to simply take out the extra bits from the connection string. I have no idea why it worked but since it worked for me, it might work for you. This is what your new connection string would look like:
using (OleDbConnection connection = new OleDbConnection(
#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathOnly + ";"))
You actually might be able to keep the HDR=Yes bit just because I understand that you might need that to tell it there are headers and I don't think leaving it in would affect it.