Get Index of the Excel Sheet using asp.net - asp.net

I am using the following code to extract the sheet names from excel: (See attached code)
But the data is returned sorted by the NAMES of the sheets, and this is the issue. I need to extract the name of the first sheet, by index.
How can I do this?
String sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + fileSavePath + newFileName + ".xls; Extended Properties='Excel 8.0;HDR=NO;'";
OleDbConnection objConn = new OleDbConnection(sConnectionString);
objConn.Open();
// Get the data table containg the schema guid.
DataTable dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string sheetName = "Sheet1$";
if (dt != null) {
try {
String[] excelSheets = new String[dt.Rows.Count];
int i = 0;
foreach (DataRow rows in dt.Rows) {
excelSheets[i] = rows["TABLE_NAME"].ToString();
i++;
}
sheetName = excelSheets[0];
}
catch {
sheetName = "Sheet1$";
}
}

try spread Sheet Gear third party component
http://www.spreadsheetgear.com

Related

C# DataTable returns blank rows

Hello I am taking data from a one datatable that is coming from a session variable and trying to dump some of the data into new datatable however the new datatable returns empty? Empty meaning that there are rows present in the new table. ie., my gridview returns several blank rows?? Not sure what is happening to the string variables?
string date = DateTime.Now.ToShortDateString();
if (Session["MyData"] != null)
{
DataTable dt = new DataTable();
dt = (DataTable)Session["MyData"];
DataTable newdt = new DataTable();
newdt.Columns.Add(new DataColumn("studentName"));
newdt.Columns.Add(new DataColumn("inter"));
newdt.Columns.Add(new DataColumn("CO"));
newdt.Columns.Add(new DataColumn("teacher"));
newdt.Columns.Add(new DataColumn("date"));
newdt.Columns.Add(new DataColumn("desc"));
DataRow newdr;
foreach (DataRow row in dt.Rows)
{
name = row["NM"].ToString();
term = row["term"].ToString();
Mark = row["Mark"].ToString();
period = row["period"].ToString();
CN = row["CN"].ToString();
CO = row["CO"].ToString();
PID = row["PID"].ToString();
//ADD TO NEW TABLE
newdr = newdt.NewRow();
name = newdr["studentName"].ToString();
dlInter.SelectedText = newdr["inter"].ToString();
CO = newdr["CO"].ToString();
teacher = newdr["teacher"].ToString();
date = newdr["date"].ToString();
LabelDescript.Text = newdr["desc"].ToString();
newdt.Rows.Add();
}
Repeater1.DataSource = newdt;
Repeater1.DataBind();
GridView1.DataSource = newdt;
GridView1.DataBind();
This line is your problem:
newdt.Rows.Add();
This will add an EMPTY row because the call to Add() without a DataRow or an object array is interpreted as adding a row without any value.
The solution is simple
newdt.Rows.Add(newdr);
Also the code before the Add is wrong because you are inverting the variables around the equal sign
newdr["studentName"] = name;
newdr["inter"] = dlInter.SelectedText;
newdr["CO"] = CO;
newdr["teacher"] = teacher
newdr["date"] = date;
newdr["desc"] = LabelDescript.Text;

Insert records in database in which have 3 foreign keys

I'm trying to insert a record in the table but the problem is in that table have 3 foreign keys. I'll be using dataTable for that but it gives an error 'There is no row position at 0'
                             
There is my code:
try
{
using (var sqlConnection = new Helpers.SqlConnectionHelpers())
{
var connection = sqlConnection.OpenConnection();
command = new SqlCommand("CarSold_Insert", connection);
command.CommandType = CommandType.StoredProcedure;
SqlCommand commandTwo = new SqlCommand("SELECT CarForSaleId, UserId, SalesPersonId FROM CarSold WHERE Price = '" + txtPrice.Text + "'", connection);
DataTable table = new DataTable();
DataSet dataSet = new DataSet();
table.Load(commandTwo.ExecuteReader());
var carForSaleId = table.Rows[0]["CarForSaleId"].ToString();
var userId = table.Rows[0]["UserId"].ToString();
var salesPersonId = table.Rows[0]["SalesPersonId"].ToString();
command.Parameters.AddWithValue("CarForSaleId", carForSaleId);
command.Parameters.AddWithValue("UserId", userId);
command.Parameters.AddWithValue("SalesPersonId", salesPersonId);
command.Parameters.AddWithValue("Price", txtPrice.Text);
command.Parameters.AddWithValue("DateSold", dateSold);
command.Parameters.AddWithValue("MonthlyPaymentDate", monthlyPaymentDate);
command.Parameters.AddWithValue("MonthlyPaymentAmount", txtPaymentAmount.Text);
//connection.Open();
int k = command.ExecuteNonQuery();
command.Parameters.Clear();
if (k != 0)
{
Response.Redirect("~/AdminPanel/CarSold.aspx");
}
else
{
lblAns.Text = "Record Not Inserted into the database";
lblAns.ForeColor = System.Drawing.Color.Red;
}
}
}
catch (Exception ex)
{
lblAns.Text = ex.Message;
}
Since Price column is float you need to write query with query parameter like this:
SqlCommand commandTwo = new SqlCommand("SELECT CarForSaleId, UserId, SalesPersonId FROM CarSold WHERE Price = #Price", connection);
commandTwo.Parameters.AddWithValue("#Price", txtPrice.Text);
The above mentioned command will give return you the carForSaleId, userId, salesPersonId which you will use in the insert command

upload a Excel file without header in Grid View (already defined column names) in asp .net C#, each time it show error when reaches at dt.Rows.Add()

here the code which i am using to import excel to grid view.. Each time getting error at dt.Rows.Add()
here the error "The string was not recognized as a valid DateTime. There is an unknown word starting at index 0.Couldn't store in SUPPLY DATE Column. Expected type is DateTime."
in .aspx page i don't defined any column with datetime
DataTable dtExl = conUpLoad.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string getExcelSheetName = dtExl.Rows[0]["Table_Name"].ToString();
OleDbCommand ExcelCommand = new OleDbCommand("Select * From [" + getExcelSheetName + "]", conUpLoad);
OleDbDataAdapter ExcelAdapter = new OleDbDataAdapter(ExcelCommand);
DataSet ExcelDataSet = new DataSet();
ExcelAdapter.Fill(ExcelDataSet);
//conUpLoad.Close();
// Clearing the grid ::::::::::::::::::::::
ViewState["dt"] = null;
GridView1.DataSource = ViewState["dt"] as DataTable;
GridView1.DataBind();
// ::::::::::::::::::::::::::::::::::::::::
DataTable dt = ExcelDataSet.Tables[0];
int i = 0;
if (ExcelDataSet.Tables[0].Rows.Count > 0)
{
String DINumber = ExcelDataSet.Tables[0].Rows[0][0].ToString();
String PartNo = ExcelDataSet.Tables[0].Rows[0][1].ToString();
String DeliveryDt = Convert.ToDateTime(ExcelDataSet.Tables[0].Rows[0][3].ToString()).ToString("dd-MMM-yyyy");
String Location = ExcelDataSet.Tables[0].Rows[0][5].ToString();
String Qty = ExcelDataSet.Tables[0].Rows[0][7].ToString();
String PartyCode = ExcelDataSet.Tables[0].Rows[0][10].ToString();
dt.Rows.Add(DINumber, PartNo, DeliveryDt, Location, Qty, PartyCode);
ViewState["dt"] = dt;
GridView1.DataSource = ViewState["dt"] as DataTable;
GridView1.DataBind();
i++;
}
else
{
GridView1.DataSource = null;
GridView1.DataBind();
}

Copying one datatable selected column to another data table

I have a datatable, then I have all the column names of the datatable as checkbox, I want to display only those column records, for which user selected from the checkbox:
Below is the code, but I am not getting the desired result
var values = "";
string clmnm = "";
for (int i = 0; i < interestedIN.Items.Count; i++)
{
if (interestedIN.Items[i].Selected)
{
values += interestedIN.Items[i].Value + ",";
}
}
values = values.TrimEnd(',');
string[] words = values.Split(',');
DataTable dt = new DataTable();
dt = (DataTable)Session["dataset"];
DataTable dt1 = new DataTable();
foreach (string word in words)
{
dt1.Columns.Add(word, typeof(string));
if (clmnm == string.Empty)
{
clmnm = word.Trim();
}
else
{
clmnm += "," +word.Trim();
}
}
foreach (DataRow dr in dt.Rows)
{
string[] split = clmnm.Split(',');
int j =0;
string str = "";
string str2 = "";
while( j < split.Length)
{
str = split[j].ToString();
if (str2 == string.Empty)
{
str2 = "dr[\""+str.ToString()+"\"]";
}
else
{
str2 += "," + "dr[\""+str.ToString()+"\"]";
}
j+=1;
}
dt1.Rows.Add(str2);
}
then I am trying to export the result as an excel sheet: but getting the below excel sheet:
There is a lot of changes to be done to your code. Lets begin with selected columns from CheckBoxList. Try using List or Arrays to store which columns that user wants. Like
List<string> columns = new List<string>();
Then store the selected columns into the columns list. Then you need to add columns to your new DataTable dt1. As,
DataTable dt1 = new DataTable();
for (int i = 0; i < interestedIN.Items.Count; i++)
{
if (interestedIN.Items[i].Selected) //If user selected this columns checkbox.
{
columns.Add(interestedIN.Items[i].Text.Trim()); //Storing values to List.
dt1.Columns.Add(interestedIN.Items[i].Text.Trim()); //Adding columns to the DataTable.
}
}
Then you can loop through your original DataTable dt and store the values as below.
foreach (DataRow dr in dt.Rows)
{
DataRow dr1 = dt1.NewRow(); // Create new row which should have identical structure for inserting.
foreach(string col in columns)
{
dr1(col) = dr(col);
}
dt1.Rows.Add(dr1); //Add the row with the contents to the table.
}

Can a gridview bound to a custom object (CSV file) be sorted?

I have a Datagrid which is getting its data from CSV. No file is sorted in any order, but I want to order the gridview by Username (a field). How could this be done? My XML/gridview code looks like the following:
Streamwriter for writing to csv and populating gridview:
string filename = #"D:\www\isolated\LocalUser\cc-suppressions\generatedsuppressions\surpressions.csv";
StreamWriter sWriter = new StreamWriter(Server.MapPath("Surpression.csv"));
string Str = string.Empty;
string headertext = "";
sWriter.WriteLine(headertext);
int cellLimit = GridView3.Rows[1].Cells.Count;
for (int i = 0; i <= (this.GridView3.Rows.Count - 1); i++)
{
for (int j = 0; j <= (this.GridView3.Rows[i].Cells.Count - 1); j++)
{
Str = this.GridView3.Rows[i].Cells[j].Text.ToString();
if (Str == " ")
Str = "";
Str = (Str + ",");
sWriter.Write(Str);
}
sWriter.WriteLine();
}
sWriter.Close();
sWriter.Dispose();
}
this.GridView3.DataBind();
You can use the ODBC driver to bind to text data. An example is
http://www.thejackol.com/2004/07/01/connect-to-a-csv-file-using-odbc-c/
You can use a data adapter to populate a DataSet object. Bind to the dataset. You should be able to sort after that.

Resources