data import from excel facing an issue - c#

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>

Related

How to show complete Excel data with Excel Headers in DataGridView? Cells becomes empty when I put headers on OleDB Connection

I want to view the Excel data with headers inside datagridview.
I have tried changing HDR=Yes to HDR=No. It shows all the data but I have headers on the Excel file.
I changed this code:
string pathconn = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=\"Excel 12.0;HDR=No;IMEX=1\";";
To:
string pathconn = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=\"Excel 12.0;HDR=No;IMEX=1\";";
This is my Excel data:
You have to put in the column name the text of the first row of the datatable.
Then delete the row.
Datatable dtExcel = importaExcelaDT(filePath);
for(int i = 0; i < dtExcel.Columns.Count; i++)
{
string columnName = dtExcel.Rows[0][i].ToString();
if (columnName == "") //throws error if column name is empty
columnName = " ";
dtExcel.Columns[i].ColumnName = columnName;
}
dtExcel.Rows.RemoveAt(0);
yourDataGridView.DataSource = dtExcel;
I get data with headers with this function.
public DataTable importaExcelaDT(string file)
{
DataTable dt = new DataTable();
DataTable dtExcel = new DataTable();
OleDbCommand cmdExcel = new OleDbCommand();
string cadenaConexion = "provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + file + "';Extended Properties = \"Excel 12.0 Xml;HDR=No;IMEX=1\";";
OleDbConnection olConexion = new OleDbConnection(cadenaConexion);
olConexion.Open();
OleDbDataAdapter oda = new OleDbDataAdapter();
dt = olConexion.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
string sheet = dt.Rows[0]["TABLE_NAME"].ToString();
cmdExcel.Connection = olConexion;
cmdExcel.CommandText = "SELECT * FROM [" + sheet + "]";
oda.SelectCommand = cmdExcel;
oda.Fill(dtExcel);
olConexion.Close();
olConexion.Dispose();
oda.Dispose();
return dtExcel;
}

How to Insert more than 1000 record using SqlBulkCopy

I need to insert more than 1000 records into SQL Server. But using my code I am able to insert only 1000 records. Please help me.
using (SqlBulkCopy s = new SqlBulkCopy(dbConnection,SqlBulkCopyOptions.UseInternalTransaction, null))
{
s.DestinationTableName = TableName;
s.BatchSize = 10000;
s.BulkCopyTimeout = 1800;
foreach (var column in dt.Columns)
{
s.ColumnMappings.Add(column.ToString(), column.ToString());
}
s.WriteToServer(dt);
}
Below is the real time working code which i used in my project to insert the bulk data from excel to the SQL server
C# code:
public static DataSet Bindgrid_StoreInSQL(string path)
{
string strFileType = Path.GetExtension(path).ToLower();
string connString = "";
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 [Sheet1$]";
OleDbConnection conn = new OleDbConnection(connString);
OleDbCommand cmd = new OleDbCommand(query, conn);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
DataTable Exceldt = ds.Tables[0];
//creating object of SqlBulkCopy
SqlBulkCopy objbulk = new SqlBulkCopy(OneStopMethods_Common.constring_Property);
//assigning Destination table name
objbulk.DestinationTableName = "Tern_boq";
objbulk.ColumnMappings.Add("ID", "ID");
objbulk.ColumnMappings.Add("Bill_No", "Bill_No");
objbulk.ColumnMappings.Add("Page_No", "Page_No");
objbulk.ColumnMappings.Add("ItemNo", "ItemNo");
objbulk.ColumnMappings.Add("Description", "Description");
objbulk.ColumnMappings.Add("BOQ_Qty", "BOQ_Qty");
objbulk.ColumnMappings.Add("UNIT", "UNIT");
objbulk.ColumnMappings.Add("Category1", "Category1");
objbulk.ColumnMappings.Add("Category2", "Category2");
objbulk.ColumnMappings.Add("Category3", "Category3");
objbulk.ColumnMappings.Add("Estimated_UnitRate", "Estimated_UnitRate");
objbulk.ColumnMappings.Add("Estimated_Amount", "Estimated_Amount");
//inserting Datatable Records to DataBase
conn.Open();
objbulk.WriteToServer(Exceldt);
SqlDatabase obj = new SqlDatabase(OneStopMethods_Common.constring_Property);
string selquery = " select * from Tern_boq";
return obj.ExecuteDataSet(CommandType.Text, selquery);
}
Its works fine,Hope this can give you some idea,Please let me know your your thoughts or suggestions

Excel File Reading External table is not in the expected format

I am generating excel file with JS,then uploading it in a temporary folder then reading it after uploading.Its giving me error " External table is not in the expected format." when I am trying to read the generated Excel file(its in xls fomat,same as with xlsx), If I make excel file in MS Excel and read it,its working fine
This is how I am generating
function GenerateExcel() {
var tab_text = $("#hdnUserData").val();
tab_text = tab_text.replace(/<A[^>]*>|<\/A>/g, ""); //remove if u want links in your table
tab_text = tab_text.replace(/<img[^>]*>/gi, ""); // remove if u want images in your table
tab_text = tab_text.replace(/<input[^>]*>|<\/input>/gi, ""); // reomves input params
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE ");
if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) // If Internet Explorer
{
txtArea1.document.open("txt/html", "replace");
txtArea1.document.write(tab_text);
txtArea1.document.close();
txtArea1.focus();
sa=txtArea1.document.execCommand("SaveAs",true,"Users Report.xls");
//sa = txtArea1.document.execCommand('SaveAs', true, 'Error Report.xsl');
}
else//other browser not tested on IE 11
sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));
return (sa);
}
the excel data in columns like this
UserID Name Username
and hidden field have data in CSV like this
1,Test,test123;2,myuser,muser1
This is how I am reading excel
using (var conn = new OleDbConnection())
{
var dt = new DataTable("dtExcel");
string importFileName = path;//Path of uploaded excel file with filename
string fileExtension = System.IO.Path.GetExtension(importFileName);
if (fileExtension == ".xls")
conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + importFileName + ";" + "Extended Properties='Excel 8.0;HDR=YES;IMEX=1;'";
if (fileExtension == ".xlsx")
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + importFileName + ";" + "Extended Properties='Excel 12.0 Xml;HDR=YES;IMEX=1;'";
conn.Open();
DataTable dtSheets = conn.GetSchema("Tables");
string firstSheet = dtSheets.Rows[0]["TABLE_NAME"].ToString();
using (var comm = new OleDbCommand())
{
comm.CommandText = "select * from [" + firstSheet + "]";
comm.Connection = conn;
using (var da = new OleDbDataAdapter())
{
da.SelectCommand = comm;
da.Fill(dt);
}
}
}
any alternative approach for reading?I have tried with stream but same error.
Error is appearing at con.Open()

in C# using oledb connection string how to Convert Scientific Notation to text strings?

I have a set of data that is downloaded as a Excel file using OLEDB connection string like so:
4552
3.00E+03
3.00E+22
3F45
3.00E+99
DD56677
37
Excel automatically thinks that 3E03, 3E22 and 3E99 are numbers and makes them look like above..
how to get it as a string ?
my code is
DataTable dataTable = new DataTable();
strExcelConn = "Provider=Microsoft.Jet.OLEDB.4.0;"
+ "Data Source=" + strFilePath + ";"
+ "Extended Properties='Excel 8.0;HDR=" + header + ";IMEX=1;TypeGuessRows=0;ImportMixedTypes=Text'";
OleDbConnection connection = new OleDbConnection(strExcelConn);
using (OleDbCommand command = new OleDbCommand())
using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
{
command.Connection = connection;
//Check if the Sheet Exists
connection.Open();
DataTable dtExcelSchema;
//Get the Schema of the WorkBook
dtExcelSchema = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
connection.Close();
connection.Open();
DataSet ds = new DataSet();
string SheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
command.CommandText = "SELECT * From [" + SheetName + "]";
adapter.SelectCommand = command;
adapter.Fill(dataTable);
connection.Close();
}
please can any one help me to get this colum as a string
Have a look at this StackOverflow question entitled How to convert a string containing an exponential number to decimal and back to string.
They use the decimal.Parse(someMoneyVar, NumberStyles.Any) method to do the conversion.
Select Excel Columns by name in your query and cast your required columns to a string using CStr(<columnName>)

Unable to read Excel worksheet with OLEDB driver

I have an excel file with one worksheet. I'm using MicroSoft.Office.Interop.Excel to read this file and then perform further execution.
Here is my code:
connString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + strNewPath + ";Extended Properties=Excel 8.0;";
conn = new OleDbConnection(connString);
if (conn.State == ConnectionState.Closed)
conn.Open();
System.Data.DataTable dt = null;
dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
But, worksheet is not in the data table object.
Where you have mentioned the table(WorkSheet) name ??
DataTable schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,
new object[] {null, null, null, "TABLE"});
//Get the First Sheet Name
string firstSheetName = schemaTable.Rows[0][2].ToString();
//Query String
string sql = string.Format("SELECT * FROM [{0}],firstSheetName);
Refer here MSDN
In case if you want to play around refer Reading Excel files from C#
OleDbConnection oconn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + "; Extended Properties=Excel 12.0;");
//After connecting to the Excel sheet here we are selecting the data
//using select statement from the Excel sheet
oconn.Open();
DataTable dbSchema = oconn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dbSchema == null || dbSchema.Rows.Count < 1)
{
throw new Exception("Error: Could not determine the name of the first worksheet.");
}
string firstSheetName = dbSchema.Rows[0]["TABLE_NAME"].ToString();
string tbstrat = "M1000";
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = oconn;
cmd.CommandText = "select * from [" + firstSheetName + "B8:" + tbstrat + "]";
OleDbDataAdapter adap = new OleDbDataAdapter();
DataTable dt = new DataTable();
adap.SelectCommand = cmd;
adap.Fill(dt);
oconn.Close();
Even you can try this
var adapter = new OleDbDataAdapter("SELECT * FROM [workSheetNameHere$]", connectionString);
var ds = new DataSet();
adapter.Fill(ds, "NameHere");
DataTable data = ds.Tables["NameHere"];

Categories