I am having two datasets in which first dataset has 6 rows and second dataset has 'N' Number of rows , second dataset row count keeps on changing , What I need is I need to export both the dataset to a single excelsheet . Both dataset has headers , So i need to export both dataset with header to a single excelsheet using c#. Can anyone help me with a sample code in c#
before u have to create
1. using Excel = Microsoft.Office.Interop.Excel;//in header,and Add correct refference
2. Excel.Application excelHandle1 = PrepareForExport(Ds); //add handle in calling function excelHandle1.Visible = true;
public Excel.Application PrepareForExport(System.Data.DataSet ds,string[] sheet)
{
object missing = System.Reflection.Missing.Value;
Excel.Application excel = new Excel.Application();
Excel.Workbook workbook = excel.Workbooks.Add(missing);
DataTable dt1 = new DataTable();
dt1 = ds.Tables[0];
DataTable dt2 = new DataTable();
dt2 = ds.Tables[1];
Excel.Worksheet newWorksheet;
newWorksheet = (Excel.Worksheet)excel.Worksheets.Add(missing, missing, missing, missing);
newWorksheet.Name ="Name of data sheet";
// for first datatable dt1..
int iCol1 = 0;
foreach (DataColumn c in dt1.Columns)
{
iCol1++;
excel.Cells[1, iCol1] = c.ColumnName;
}
int iRow1 = 0;
foreach (DataRow r in dt1.Rows)
{
iRow1++;
for (int i = 1; i < dt1.Columns.Count + 1; i++)
{
if (iRow1 == 1)
{
// Add the header the first time through
excel.Cells[iRow1, i] = dt1.Columns[i - 1].ColumnName;
}
excel.Cells[iRow1 + 1, i] = r[i - 1].ToString();
}
}
// for second datatable dt2..
int iCol2 = 0;
foreach (DataColumn c in dt2.Columns)
{
iCol2++;
excel.Cells[1, iCol] = c.ColumnName;
}
int iRow2 = 0;
foreach (DataRow r in dt2.Rows)
{
iRow2++;
for (int i = 1; i < dt2.Columns.Count + 1; i++)
{
if (iRow2 == 1)
{
// Add the header the first time through
excel.Cells[iRow2, i] = dt2.Columns[i - 1].ColumnName;
}
excel.Cells[iRow2 + 1, i] = r[i - 1].ToString();
}
}
return excel;
}
First you have to declare namespace:
using Excel = Microsoft.Office.Interop.Excel;
public static void Main(string[] args) {
DataTable dt1 = new DataTable("Employee");
dt1.Columns.Add("Employee ID");
dt1.Columns.Add("Employee Name");
dt1.Rows.Add("1", "ABC");
dt1.Rows.Add("2", "DEF");
dt1.Rows.Add("3", "PQR");
dt1.Rows.Add("4", "XYZ");
DataTable dt3 = new DataTable("Department");
dt3.Columns.Add("Department ID");
dt3.Columns.Add("Department Name");
dt3.Rows.Add("1", "IT");
dt3.Rows.Add("2", "HR");
dt3.Rows.Add("3", "Finance");
DataSet ds = new DataSet();
ds.Tables.Add(dt1);
ds.Tables.Add(dt3);
Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
Excel._Worksheet worksheet = null;
app.Visible = false;
worksheet = workbook.Sheets["Sheet1"];
worksheet = workbook.ActiveSheet;
worksheet.Name = "Exported from gridview";
int z = 1;
for (int x = 0; x < ds.Tables.Count; x++)
{
int r = z;
int t = r + 1;
for (int i = 1; i < ds.Tables[x].Columns.Count + 1; i++)
{
worksheet.Cells[r, i] = ds.Tables[x].Columns[i - 1].Caption;
}
for (int i = 0; i < ds.Tables[x].Rows.Count; i++)
{
for (int j = 0; j < ds.Tables[x].Columns.Count; j++)
{
worksheet.Cells[i + t, j + 1] = ds.Tables[x].Rows[i]
[j].ToString();
}
}
z = ds.Tables[x].Rows.Count + 3;
}
string textPath = "e:\\output.xls";
if (File.Exists(textPath))
{
File.Delete(textPath);
}
workbook.SaveAs(textPath, Type.Missing, Type.Missing, Type.Missing,
Type.Missing,
Type.Missing,
Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive,
Type.Missing, Type.Missing, Type.Missing, Type.Missing);
app.Quit();
}
Related
I have an export function in my asp.net application. I want to remove all the white spaces/nulls in the list. Any way to trim it?
This is how my code looks like:
My GetData methode from the Database:
public void GetData()
{
try
{
DataTable dt = new DataTable();
SqlConnection connection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["GS1connectionString"].ConnectionString);
connection.Open();
using (SqlCommand sqlCmd = new SqlCommand("DAtabase.dbo.SP_EXPORT", connection)) //Extract data: no cons first and cons after
{
sqlCmd.CommandType = CommandType.StoredProcedure;
using (SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd))
{
sqlDa.Fill(dt);
if (dt.Rows.Count > 0)
{
Session["TaskTable"] = dt;
}
}
}
}
catch (Exception)
{
Page.ClientScript.RegisterStartupScript(GetType(), "msgbox", "alert('No data found, try again');", true);
}
}
Clean dataTable methode:
public DataTable removeEmptyColumns(DataTable table)
{
int k = 0, l = 0;
DataTable dtResult = table.Clone();
DataRow row = dtResult.NewRow();
row = dtResult.NewRow();
for (k = 0; k < table.Rows.Count; k++)
{
for (l = 0; l < table.Rows.Count; l++)
{
if (k == l)
row[k] = table.Rows[k][l];
}
}
dtResult.Rows.Add(row);
dtResult.AcceptChanges();
return dtResult;
}
The Export to excel button:
protected void Button_Export_DS_Click(object sender, EventArgs e)
{
GetData();
DataTable dat = new DataTable();
DataTable dtNew = new DataTable();
dat = (DataTable)Session["TaskTable"];
dtNew = removeEmptyColumns(dat);
//Export to excel from datatable stored in a session
if (dtNew.Rows.Count > 0)
{
MemoryStream ms = new MemoryStream();
int i = 1;
using (ExcelPackage package = new ExcelPackage(ms))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Sheet" + i++);
worksheet.Cells["A1"].LoadFromDataTable(dtNew, true);
worksheet.Cells.AutoFitColumns();
Response.Clear();
package.SaveAs(Response.OutputStream);
Response.AddHeader("content-disposition", "attachchment; filename=DS_Export.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.xls";
Response.End();
}
}
}
I have an export function in my asp.net application. I want to remove all the white spaces/nulls in the list. Any way to trim it?
You copy and paste this function:
public DataTable removeEmptyColumns(DataTable table)
{
int k = 0, l = 0;
DataTable dtResult = table.Clone();
DataRow row = dtResult.NewRow();
row = dtResult.NewRow();
for (k = 0; k < table.Rows.Count ; k++)
{
for (l = 0; l < table.Rows.Count; l++)
{
if (k == l)
row[k] = table.Rows[k][l];
}
}
dtResult.Rows.Add(row);
dtResult.AcceptChanges();
return dtResult;
}
And then use the function like this:
DataTable dt = new DataTable();
DataTable dtNew = new DataTable();
dt = (DataTable)Session["TaskTable"];
dtNew = removeEmptyColumns(dt);
After that, use this dtNew in this:
if (dtNew.Rows.Count > 0)
{
MemoryStream ms = new MemoryStream();
int i = 1;
using (ExcelPackage package = new ExcelPackage(ms))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Sheet" + i++);
worksheet.Cells["A1"].LoadFromDataTable(dtNew, true);
worksheet.Cells.AutoFitColumns();
Response.Clear();
package.SaveAs(Response.OutputStream);
Response.AddHeader("content-disposition", "attachchment; filename=Export.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.xls";
Response.End();
}
}
I am trying to use a tool tip on every row of a grid to show details whenever user place pointer on particular cell. It's supposed to show details for every row but it only shows details for the first row. Can any one help me?
for (int i = 1; i <= e.Row.Cells.Count - 1; i++)
{
if (e.Row.Cells[i].Text == "0" || string.IsNullOrEmpty(e.Row.Cells[i].Text) || e.Row.Cells[i].Text == " ")
{
e.Row.Cells[i].Text = "";
}
else
{
e.Row.Cells[i].BackColor = System.Drawing.Color.Blue;
dateSetExport.Tables.Clear();
dateSetExport.Reset();
SqlParameter[] param = new SqlParameter[2];
param[1] = new SqlParameter("#Startdate", gvDetails.HeaderRow.Cells[i].Text);
param[0] = new SqlParameter("#Employe_Id", e.Row.Cells[0].Text.Split('-')[0]);
DataTable dt1 = DataHelper.getDataTableExecuteSP("usp_GetToolTip", param);
dt1.TableName = "ToolTip";
dateSetExport.Tables.Add(dt1);
string tooltip = "";
for (int j = 0; j < dt1.Rows.Count; j++)
{
tooltip = tooltip + dt1.Rows[j]["normal_working_hours"].ToString() + " Hours : " + dt1.Rows[j]["description"].ToString()+"\n\n";
}
e.Row.Cells[i].ToolTip = tooltip;
}
}
You can use another foreach in order to loop all rows :
foreach (GridViewRow row in GridView.Rows)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//do your staff
}
}
But for me, you should use GridView_RowDataBound event :
protected void GridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
for (int i = 1; i <= e.Row.Cells.Count - 1; i++)
{
if (e.Row.Cells[i].Text == "0" || string.IsNullOrEmpty(e.Row.Cells [i].Text) || e.Row.Cells[i].Text == " ")
{
e.Row.Cells[i].Text = "";
}
else
{
e.Row.Cells[i].BackColor = System.Drawing.Color.Blue;
dateSetExport.Tables.Clear();
dateSetExport.Reset();
SqlParameter[] param = new SqlParameter[2];
param[1] = new SqlParameter("#Startdate", gvDetails.HeaderRow.Cells[i].Text);
param[0] = new SqlParameter("#Employe_Id", e.Row.Cells[0].Text.Split('-')[0]);
DataTable dt1 = DataHelper.getDataTableExecuteSP("usp_GetToolTip", param);
dt1.TableName = "ToolTip";
dateSetExport.Tables.Add(dt1);
string tooltip = "";
for (int j = 0; j < dt1.Rows.Count; j++)
{
tooltip = tooltip + dt1.Rows[j]["normal_working_hours"].ToString() + " Hours : " + dt1.Rows[j]["description"].ToString()+"\n\n";
}`enter code here`
e.Row.Cells[i].ToolTip = tooltip;
}
}
}
}
#region fillAllData4
private void fillAllData4()
{
clsCategory objCategory = new clsCategory(true);
clsProductMain objProduct = new clsProductMain(true);
objCategory.getDropDownMenu();
objProduct.getProduct();
string str = string.Empty;
int i = 0;
// int j = 0;
if (objCategory.ListclsCategory.Count > 0)
{
for (i = 0; i < objCategory.ListclsCategory.Count; i++)
{
cat.InnerHtml = objCategory.ListclsCategory[0].CategoryName;
cat1.InnerHtml = objCategory.ListclsCategory[1].CategoryName;
cat2.InnerHtml = objCategory.ListclsCategory[2].CategoryName;
cat3.InnerHtml = objCategory.ListclsCategory[3].CategoryName;
string[] filePaths = Directory.GetFiles(Server.MapPath("~/images/Saree/"));
int j = 0;
foreach (string filePath in filePaths)
{
string fileName = Path.GetFileName(filePath);
str += #"<div><div><img class='imges' src='images/Saree/" + fileName + #"' /></div>
<div class='sname'>" + objProduct.ListclsProductMain[j].ProductName + #"</div>
<div class='sname2'>" + objProduct.ListclsProductMain[j].MRP + #"</div></div>";
j++;
}
slider3.InnerHtml = str;
slider4.InnerHtml = str;
slider5.InnerHtml = str;
slider6.InnerHtml = str;
//System.Web.UI.HtmlControls.HtmlGenericControl createDiv =
//new System.Web.UI.HtmlControls.HtmlGenericControl("DIV");
//createDiv.ID = "createDiv";
//createDiv.InnerHtml =str;
//this.Controls.Add(createDiv);
}
}
}
#endregion
I have two repeater controls one inside other and in inner repeater there is placeholder in which radio button is dynamically generated. I want to find the radio button control to check whether it is checked or not? I want above all function to be performed in button submit/click event defined in the code?
if (!Page.IsPostBack)
{
//1) Load SomeDatatable from Database somehow
// Just for testing : replace with query to DB
strqry = "select * from Quiz_tblQsnsLimitMaster where Qsnexamname='" + Request.QueryString["QsnEname"].ToString() + "'";
SqlDataAdapter adp = new SqlDataAdapter(strqry, sCon);
DataSet ds = new DataSet();
try
{
adp.Fill(ds);
int total = ds.Tables[0].Rows.Count;
for (int i = 0; i < total; i++)
{
string QuesID = ds.Tables[0].Rows[i].ItemArray[1].ToString();
//SubName = ds.Tables[0].Rows[i].ItemArray[3].ToString();
DataSet oDs = SqlHelper.ExecuteDataset(sCon, "Ps_Quiz_OnlineTest_QuestionsWithOptions_Get", QuesID);
SomeDatatable.Merge(oDs.Tables[0]);
}
removeDuplicatesRows(SomeDatatable);
System.Data.DataColumn newColumn = new System.Data.DataColumn("ContentIndex", typeof(System.String));
newColumn.DefaultValue = "0";
SomeDatatable.Columns.Add(newColumn);
for (int i = 0; i < Math.Ceiling((decimal)SomeDatatable.Rows.Count); i++)
SomeDatatable.Rows[i]["ContentIndex"] = i + 1;
}
catch
{
}
////2) Create a dummy data source for the tab repeater using a list of anonymous types
List<object> TabList = new List<object>();
//BindSubject();
for (int I = 0; I < Math.Ceiling((decimal)SomeDatatable.Rows.Count / (decimal)ContentPerTab); I++)
{
TabList.Add(new { TabIndex = I });
}
TabRepeater.ItemDataBound += TabRepeater_ItemDataBound;
TabRepeater.DataSource = TabList;
TabRepeater.DataBind();
//TablLinkRepeater.DataSource = TabList;
//TablLinkRepeater.DataBind();
//}
}
public void removeDuplicatesRows(DataTable dt)
{
SomeDatatable = dt.DefaultView.ToTable(true, "QuestionId");
}
protected void TabRepeater_ItemDataBound(object sender, System.Web.UI.WebControls.RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item | e.Item.ItemType == ListItemType.AlternatingItem)
{
int TabIndex = -1;
int.TryParse(DataBinder.Eval(e.Item.DataItem, "TabIndex").ToString(), out TabIndex);
//Copy Content Rows from SomeDatable that belong to this tab
DataTable Dt = SomeDatatable.Clone();
for (Int32 i = TabIndex * ContentPerTab; i <= (TabIndex + 1) * ContentPerTab - 1; i++)
{
if (i >= SomeDatatable.Rows.Count) break;
Dt.ImportRow(SomeDatatable.Rows[i]);
}
// Find the content repeater in this item and use the new datatable as source
Repeater ContentRepeater = (Repeater)e.Item.FindControl("ContentRepeater");
ContentRepeater.ItemDataBound += ContentRepeater_ItemDataBound;
ContentRepeater.DataSource = Dt;
ContentRepeater.DataBind();
}
}
// This handler might be needed for content repeater, included just for testing
protected void ContentRepeater_ItemDataBound(object sender, System.Web.UI.WebControls.RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item | e.Item.ItemType == ListItemType.AlternatingItem)
{
//Read coulmn from Datarow
int ContentIndex = -1;
int.TryParse(DataBinder.Eval(e.Item.DataItem, "ContentIndex").ToString(), out ContentIndex);
var parsed = "'" + HttpUtility.ParseQueryString(DataBinder.Eval(e.Item.DataItem, "QuestionID").ToString()) + "'";
//Add Question
DataSet ds = SqlHelper.ExecuteDataset(sCon, "Ps_Quiz_QuestionsWithOptions_Get", Convert.ToString(parsed));
if (ds.Tables.Count > 0)
{
if (ds.Tables[0].Rows.Count > 0)
{
int iCnt = 0;
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
Table tblQsn = new Table();
//.....Begin Text Qsn Creation.....//
tblQsn.Width = new Unit("98%");
TableRow trQsn = new TableRow();
iRowCounter++;
trQsn.ID = "Row_" + iRowCounter.ToString();
TableCell tcQsn = new TableCell();
TableCell tcQsnSNo = new TableCell();
tcQsn.CssClass = "Label";
tcQsn.BackColor = System.Drawing.Color.Gainsboro;
tcQsn.Font.Bold = true;
tcQsn.Font.Size = 12;
tcQsn.Text = ds.Tables[0].Rows[i][1].ToString();
tcQsn.Width = Unit.Percentage(99.5);
iCellCounter++;
tcQsn.ID = "Cell_" + iCellCounter.ToString();
tcQsnSNo.CssClass = "Label";
tcQsnSNo.Attributes.Add("valign", "top");
tcQsnSNo.BackColor = System.Drawing.Color.Gainsboro;
tcQsnSNo.Font.Bold = true;
tcQsnSNo.Width = Unit.Percentage(0.5);
iCellCounter++;
tcQsnSNo.ID = "Cell_" + iCellCounter.ToString();
iCnt++;
tcQsnSNo.Text = ContentIndex.ToString() + ".";
trQsn.Cells.Add(tcQsnSNo);
trQsn.Cells.Add(tcQsn);
tblQsn.Rows.Add(trQsn);
int rcnt = i;
int iOptCnt = 0;
string sStatus = "N";
while ((rcnt >= 0) && (rcnt < ds.Tables[0].Rows.Count))
{
if (ds.Tables[0].Rows[rcnt][2].ToString() == ds.Tables[0].Rows[i][2].ToString())
{
if (sStatus == "N")
{
sStatus = "Y";
}
TableRow trQsnOpt = new TableRow();
iRowCounter++;
trQsnOpt.ID = "Row_" + iRowCounter.ToString();
TableCell tcQsnOpt = new TableCell();
tcQsnOpt.CssClass = "Label";
iCellCounter++;
tcQsnOpt.ID = "Cell_" + iCellCounter.ToString();
tcQsnOpt.Attributes.Add("valign", "top");
tcQsnOpt.VerticalAlign = VerticalAlign.Middle;
TableCell tcQsnOptSNo = new TableCell();
tcQsnOptSNo.CssClass = "Label";
iCellCounter++;
tcQsnOptSNo.ID = "Cell_" + iCellCounter.ToString();
iOptCnt++;
RadioButton oRbOptions = new RadioButton();
oRbOptions.GroupName = ds.Tables[0].Rows[rcnt][2].ToString() + "_Group";
oRbOptions.Text = ds.Tables[0].Rows[rcnt][3].ToString().Trim();
oRbOptions.Font.Size = 11;
iRbTCounter++;
oRbOptions.ID = ds.Tables[0].Rows[i][0].ToString() + "_" + ds.Tables[0].Rows[rcnt][2].ToString() + "_" + "Option" + iOptCnt.ToString() + "_" + iRbTCounter.ToString();
//oRbOptions.Enabled = false;
//if (ds.Tables[0].Rows[i][2].ToString() == "Option" + iRbTCounter.ToString())
//{
// oRbOptions.Checked = true;
//}
oRbOptions.InputAttributes.Add("data-info", Convert.ToString(ContentIndex));
oRbOptions.CssClass = "Label";
tcQsnOpt.Controls.Add(oRbOptions);
tcQsnOptSNo.Text = iOptCnt.ToString() + ".";
trQsnOpt.Cells.Add(tcQsnOptSNo);
trQsnOpt.Cells.Add(tcQsnOpt);
rcnt++;
//.....Add Option Image.....//
tblQsn.Rows.Add(trQsnOpt);
}
else
break;
}
i = rcnt - 1;
PlPreview = (PlaceHolder)e.Item.FindControl("PlPreview");
PlPreview.Controls.Add(tblQsn);
}
}
}
}
}
protected void btnsubmit_Click(object sender, EventArgs e)
{
SubmitQuestion();
}
public void SubmitQuestion()
{
for (int c = 0; c < SomeDatatable.Rows.Count; c++)
{
string sQsnOptId = SomeDatatable.Rows[c]["QuestionID"].ToString();
DataSet ds = SqlHelper.ExecuteDataset(sCon, "Ps_Quiz_QuestionsWithOptions_Get", "'" + sQsnOptId + "'");
for (int i = 1; i <= 4; i++)
{
string rdboption = ds.Tables[0].Rows[c][0].ToString() + "_" + ds.Tables[0].Rows[i-1][2].ToString() + "_" + "Option" + i + "_" + i;
Repeater rpt = (Repeater)TabRepeater.NamingContainer.FindControl("ContentRepeater");
RadioButton rbt = (RadioButton)rpt.NamingContainer.FindControl(rdboption);
if (rbt.Checked)
{
strqry = "update Quiz_tblOnlineTest_Detail set UserAns='Option" + i + "', DeletionStatus='A' where CreationLogInId='AMITSAMBYAL#HOTMAIL.COM' and ExamName='" + Request.QueryString["QsnEname"].ToString() + "' and QsnId=" + Session["quesid"].ToString() + "";
cmd = new SqlCommand(strqry, con);
try
{
cmd.ExecuteNonQuery();
}
catch
{
}
finally
{
con.Close();
}
break;
}
}
}
}
}
I found the answer. Thanks
foreach (RepeaterItem repeater in TabRepeater.Items)
{
Repeater repeater1 = (Repeater)repeater.FindControl("ContentRepeater");
foreach (RepeaterItem repItem in repeater1.Items)
{
for (int i = 1; i <= 4; i++)
{
string rdboption = ds.Tables[0].Rows[c][0].ToString() + "_" + ds.Tables[0].Rows[i - 1][2].ToString() + "_" + "Option" + i + "_" + i;
PlaceHolder PlPreview = (PlaceHolder)repItem.FindControl("PlPreview");
rbt = (RadioButton)PlPreview.FindControl(rdboption);
if (rbt.Checked)
{
// statement
}
}
}
}
}
}
This is my code:
DataSet dsCategoryRes = new DataSet();
dsCategoryRes = oCourse.SubscribedResources(Profile.UserName, CustomerId, "0", 0);
DataTable dt = dsCategoryRes.Tables[0];
DataView dv = new DataView(dt);
Int32 maxCnt;
if (dv.Table.Rows.Count <= 5)
maxCnt = dv.Table.Rows.Count - 1;
else
maxCnt = 4;
int cnt;
for (cnt = 0; cnt <= maxCnt; cnt++)
{
dv.Sort = "CategoryName DESC";
//dv.Table.Rows.Cast<System.Data.DataRow>().Take(5);
dt = dv.ToTable();
dt.Rows.Cast<System.Data.DataRow>().Take(5);
rptSub.DataSource = dt;
rptSub.DataBind();
}
Using this am to able to sort in descending order but i am not able to select the top 5 values.
Something like this?
var dt = new DataTable();
dt.Columns.Add("ID", typeof(Int32));
dt.Columns.Add("Name");
//Creating some dummy data
for (int i = 0; i < 10; i++)
{
var newRow = dt.NewRow();
newRow["ID"] = i;
newRow["Name"] = "dummyData" + i;
dt.Rows.Add(newRow);
}
var dt2 = new DataTable();
dt2 = (from rows in dt.AsEnumerable().OrderByDescending(x => x.Field<int>("ID")) select rows).Take(5).CopyToDataTable();