Excel Data to gridview ? In Asp.net? - asp.net

In web application, i am trying to get the data from excel and bind to gridview, it is working fine, but when the excel contain the row whcih is having only single value in the cell and remaing cells are empty then it is showing default letters like [F, G, H..] like in top of the gridview header.The below is the actual excel Sheet
below is the excel sheet format
This is my code which is in page load even
System.Data.DataTable dt = null;
string excelFile = Server.MapPath("./performances.xls");
DataSet ds = new DataSet();
// Connection String.
String connString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + excelFile + ";Extended Properties=Excel 8.0;";
// Create connection.
oledbConn = new OleDbConnection(connString);
// Opens connection with the database.
oledbConn.Open();
// Get the data table containing the schema guid, and also sheet names.
dt = oledbConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
return;
}
String[] excelSheets = new String[dt.Rows.Count];
int i = 0;
// Add the sheet name to the string array.
// And respective data will be put into dataset table
foreach (DataRow row in dt.Rows)
{
excelSheets[i] = row["TABLE_NAME"].ToString();
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [" + excelSheets[i] + "]", oledbConn);
OleDbDataAdapter oleda = new OleDbDataAdapter();
oleda.SelectCommand = cmd;
oleda.Fill(ds, "TABLE");
i++;
}
// Bind the data to the GridView
grdMygrd .DataSource = ds.Tables[0].DefaultView;
grdMygrd.DataBind();
Session["Table"] = ds.Tables[0];

I have repeated your error, and it looks to me that it's a problem with the excel format. the headers in the excel document are simple merged cells, the OleDB data provider sees those cells as separate empty values, and the headers that consist of merged cells, have their values in the bottom cells. the possible solution would be to try and flatten the headers in excel, and manually paint them on your page.
it would figure, because the OleDB data provider sees the excel file as a database, and those do not actually have sub-headers.

Related

Data type mismatch exception when trying to compare excel rows of general or type to a string using OleDbCommand

In order to make my application faster, I am trying to fetch a row where the 'Vertical_num' column matches the given string.The below code
using (OleDbConnection connection = new OleDbConnection(con))
{
connection.Open();
OleDbCommand command = new OleDbCommand("Select * from [All Verticals$] where Vertical_num ='"+t+"'", connection);
OleDbDataAdapter da = new OleDbDataAdapter(command);
DataSet ds = new DataSet();
System.Data.DataTable dt1 = new System.Data.DataTable();
da.Fill(dt1);
for (int i=0;i<dt1.Rows.Count;i++)
{
Console.Out.WriteLine(dt1.Rows[i].ItemArray[2].ToString());
}
connection.Close();
}
It prints the required value when the value in my excel file column is 1000_1 but when the value in the column is 10001 it returns "Data type mismatch exception"
How can I modify my query to match all types of cell value?
The type of my excel column is general, I changed it to text but the same error was returned.

Comparing cyrillic data from SQL Server table and Excel file with ASP.NET

Using ASP.NET I need to compare data loaded from Excel file with data in SQL Server table. It's data written in cyrillic.
Basically, after script creates an array list filled with data from database table, it opens Excel file, and list data from one of the column. For every data stored in Excel cell, I have to find position in mentioned array list.
I have same data in both sources, but script returns that there are no same data at all. I guess that is something related with cyrillic letters.
Part of the code used for reading Excel cells and comparing with array list looks like this:
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 + "]";
Page.Trace.Write(getExcelSheetName);
dAdapter.SelectCommand = cmd;
dAdapter.Fill(dtExcelRecords);
con.Close();
foreach (DataRow row in dtExcelRecords.Rows)
{
Response.Write(row[0]);
Response.Write(" ");
Response.Write(MyClass.areasList.IndexOf(row[0])); // always returns -1
Response.Write(Environment.NewLine);
Response.Write("<br />");
}
Can you help me solving this please? Thank you in advance!

Import excel file to sql server in asp.net with check existing record in table before import

Sorry my Enghist is not good!
How to check excel fie, if a row existing in table do'nt import this row
My function work well for import (not check existing)
string excelConnectionString = "";
string strFileName = DateTime.Now.ToString("ddMMyyyy_HHmmss");
string strFileType = System.IO.Path.GetExtension(fileuploadExcel.FileName).ToString().ToLower();
fileuploadExcel.SaveAs(Server.MapPath("~/Import/" + strFileName + strFileType));
string strNewPath = Server.MapPath("~/Import/" + strFileName + strFileType);
//Connection String to Excel Workbook
if (strFileType.Trim() == ".xls")
{
excelConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strNewPath + ";Extended Properties=Excel 8.0;Persist Security Info=False";
}
else if (strFileType.Trim() == ".xlsx")
{
excelConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strNewPath + ";Extended Properties=Excel 12.0;Persist Security Info=False";
}
//Create Connection to Excel work book
OleDbConnection excelConnection =new OleDbConnection(excelConnectionString);
//Create OleDbCommand to fetch data from Excel
OleDbCommand cmd = new OleDbCommand("Select [account_id], [type],[first_name], [last_name], [title], [birthday], [tel],[phone], [email_1],[email_2], [remark],[del_if] from [Sheet1$]",excelConnection);
excelConnection.Open();
OleDbDataReader dReader;
dReader = cmd.ExecuteReader();
SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection);
//Give your Destination table name
sqlBulk.DestinationTableName = "contact";
sqlBulk.WriteToServer(dReader);
I don't know if this is going to be possible using SqlBulkCopy. What you could do, is write the data to a staging table, and only copy across the records that don't already exist. Then you can clear out the staging table once your copy is complete.
Edit:
Given your comment about not wanting to use a staging table, you could possibly find a distinct list of key values (possibly account_id from your example) from your "contact" table before reading data from the excel file, and then use the list to exclude records you read from the excel file. The benefits to this are you aren't reading data from the excel file that you don't need to. The downside is that this might not be all that efficient if your "contact" table is huge or if the key you'd use to compare the data isn't something simple like account_id.
Another alternative could be, if you're excel file isn't huge, to insert records row by row using a where clause on the insert to ensure the insert won't create unnecessary duplicates. This will be significantly slower than SqlBulkCopy, but it'll work.

asp.net how to decrypt each label value in a gridview

i have an gridview that retrieves the data via a datatable like this:
protected DataTable allClients()
{
string conn, comm, tSub, tMain;
tSub = "client_sub";
tMain = "client_main";
conn = ConfigurationManager.ConnectionStrings["localsqlserver"].ConnectionString;
comm = "SELECT * FROM [" + tSub + "] t1 LEFT JOIN [" + tMain + "] t2 ON " +
"t1.customer_ID = t2.customer_ID";
SqlConnection connection = new SqlConnection(conn);
SqlCommand cmd = new SqlCommand(comm, connection);
connection.Open();
DataTable allTable = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(allTable);
connection.Close();
return allTable;
}
clientGrid.DataSource = allClients();
clientGrid.DataBind();
and its working fine on retrieving the data but the problem is i am trying to decrypt the value on retrieving it.
i used this encryptor class
so how can decrypt the value of each row in the gridview.
using asp.net 4.0, thanks
Two options - you can loop around the data table in your allClients() method before returning it, or you can look into handling the row bound events when you do the data bind on the grid view - this would allow you to access each row as its created in the grid view and manipulate the data displayed.

Numbers ignored when importing Excel to SQL Server in ASP.NET using OLEDB

Here's the code I'm using to show the Excel data on a Gridview:
if (FileUploadExcel.PostedFile.FileName.Contains(".xls"))
{
FileUploadExcel.SaveAs(Server.MapPath("~/Upload/") + "data.xls");
string connectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("~/Upload/") + "data.xls;Extended Properties=Excel 8.0;";
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
connection.Open();
OleDbCommand command = new OleDbCommand("Select ID FROM [Sheet1$]", connection);
DataTable raw = new DataTable();
using (System.Data.Common.DbDataReader dr = command.ExecuteReader())
{
raw.Load(dr);
}
gv.DataSource = raw;
gv.DataBind();
}
}
This is what happens... I have this in my data.xls file:
ID
A-001
3929
B-001
When I upload that, the Gridview displays only these:
ID
A-001
B-001
Is there anything wrong with the code? Thanks.
Try to add IMEX=1 to your connection string.
It tells the driver to always read "intermixed" (numbers, dates, strings etc) data columns as text. Note that this option might affect excel sheet write access negative.
http://www.connectionstrings.com/excel

Resources