I have a repeater which has some controls which are checkboxes. I would like to copy all items in the repeater except the checkboxes, where in their place i will copy the value of teh checkbox. THe purpose is that I would like to export all of the information from the repeater to an excel document in xls format. However, this does not allow me to have checkboxes, thus the reason I want to remove them.
How should I do this please?
I have tried:
for (int j =0; j<repeater1.Items.Count; j++)
{
RepeaterItem repItem = repeater1.Items[j];
foreach (Control c in repItem.Controls)
{
if (!(c is CheckBox))
{
Control c2 = c;
repeater2.Items[j].Controls.Add(c2);
}
}
}
But it gives me this error:
Collection was modified; enumeration operation may not execute.
You wrote in the comment, that you want to export your repeater that has a checkbox. It is not allowed to export a checkbox to excel and that's why you want to remove the checkbox before exporting.
Here is one way you can do this... just add this in your page and try....
public override void VerifyRenderingInServerForm(Control control)
{
}
Alternatively what if you export your DataTable instead of the repeater ?
If the above is not working and you want to iterate and then export then here is code...
protected void btnExport_Click(object sender, EventArgs e)
{
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
string attachment = "attachment; filename=FileName" + DateTime.Now.ToString() + ".xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
foreach (RepeaterItem item in Repeater1.Items)
{
CheckBox chk= item.FindControl("CheckBox") as CheckBox;
chk.Visible = false;
}
Repeater1.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
Related
I have a button which helps me export a Gridview to an excel file. Now along with exporting the GridView, I also want the button to add an
empty row on top of the excel file such that the Gridview only starts from the 2nd row. How can I do that? Any help will be greatly appreciated!
So far, I have this snippet which helps me export my Gridview perfectly.
protected void btnOk_Click(object sender, EventArgs e)
{
Response.ClearContent();
Response.AppendHeader("content-disposition", "attachment;
filename=Test.xls");
Response.ContentType = "application/excel";
System.IO.StringWriter stringWriter = new System.IO.StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(stringWriter);
GridView1.RenderControl(htw);
Response.Write(stringWriter.ToString());
Response.End();
}
In application i have grid view and Ajax Toolkit control linechart i need to export grid view and linechart to excel sheet(open office/Libra office). i tried some code in export button but what happens grid view is exported but line chart is not export to excel. my page appear like this [my chart image]
by clicking the export button then only grid view will export to excel but not linechart it will not export.what i need is chart should be export to excel. how to do this
i tried code is:
.aspx:
<cc1:LineChart ID="LineChart1" runat="server" ChartHeight="300" ChartWidth="900" ChartType="Basic" ChartTitleColor="#0E426C" Visible="true" CategoryAxisLineColor="#D08AD9" ValueAxisLineColor="#D08AD9" BaseLineColor="#A156AB"></cc1:LineChart>
.cs:
protected void btnExport_Click(object sender, EventArgs e)
{
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "filename.xls"));
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
base.OnPreRender(e);
ScriptManager sm = ScriptManager.GetCurrent(Page);
sm.RegisterScriptControl(LineChart1);
LineChart1.Visible = true;
for (int i = 0; i < grdview1.HeaderRow.Cells.Count; i++)
{
grdview1.HeaderRow.Cells[i];
}
grdview1.RenderControl(htw);
LineChart1.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}
I added OnPreRender() for Registering the scriptmanager control
protected override void OnPreRender(EventArgs e)
{
/* Verifies that the control is rendered */
base.OnPreRender(e);
ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
if (scriptManager == null)
{
scriptManager = new ScriptManager();
scriptManager.ID = "ScriptManager1";
scriptManager.EnablePartialRendering = true;
Controls.AddAt(0, scriptManager);
}
}
Can anyone help me out how can i export linechart.
Thank you
No, you can not export LineChart.
In my page I have two textbox controls, where I am gating the date from the Calendar Extender & in the export to excel Button I am going to export the Gridview data to excel sheet.
When I am gating the excel sheet its show the the textbox & button also from which i am export the excel Sheet.
I have written the export code in the Export Button.
Like:-
protected void Export_to_Excel_Click(object sender, EventArgs e)
{
try
{
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Customers.xls"));
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
Grd_MidData.AllowPaging = false;
bindgriddata();
//Change the Header Row back to white color
Grd_MidData.HeaderRow.Style.Add("background-color", "#FFFFFF");
//Applying stlye to gridview header cells
for (int i = 0; i < Grd_MidData.HeaderRow.Cells.Count; i++)
{
Grd_MidData.HeaderRow.Cells[i].Style.Add("background-color", "#df5015");
}
Grd_MidData.RenderControl(htw);
Response.Write(sw.ToString());
Response.Flush();
}
catch (Exception ee)
{
}
}
When I am gating the excel sheet it shows the gridview data along with the two text box & the button from where I am doing the filtering.
So any one suggest me, How to show only the gridview data but not show the Textbox & button on the excel sheet.
You have to bind the data to your excel code,
using below code
bindgriddata();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Customers.xls"));
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter ht = new HtmlTextWriter(sw);
Grd_MidData.RenderControl(ht);
Response.Write(sw.ToString());
Response.End();
it is working for me.
Here the gridview data is showing along with the From date: To Date: textbox & the button also. So how can i remove these field from the sheet.
you can use close xml to generate excel it will give more functionlity to create excel and formatting.
protected void Export_to_Excel_Click(object sender, EventArgs e)
{
bindgriddata();
Grd_MidData.DataSource = objDS; // Dataset
Grd_MidData.DataBind();
using (XLWorkbook wb = new XLWorkbook())
{
try
{
//creating worksheet
var ws = wb.Worksheets.Add("Report");
//adding columms header
int columnscount = objDS.Tables[0].Columns.Count;
char a = 'A';
for (int j = 1; j <= columnscount; j++)
{
string str = a + "1";
ws.Cell(str).Value = objDS.Tables[0].Columns[j - 1].ColumnName.ToString();
ws.Cell(str).Style.Border.OutsideBorder = XLBorderStyleValues.Thin;
a++;
}
ws.Columns().AdjustToContents();
//formatting columns header
var rngheaders = ws.Range("A1:J1");
rngheaders.FirstRow().Style
.Font.SetBold()
.Font.SetFontSize(12)
.Font.SetFontColor(XLColor.Black)
.Fill.SetBackgroundColor(XLColor.DeepSkyBlue)
.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center)
.Border.OutsideBorder = XLBorderStyleValues.Thin;
////adding data to excel
int k = 2;
foreach (DataRow row in objDS.Tables[0].Rows)
{
char b = 'A';
string str = b + "" + k;
for (int i = 0; i < objDS.Tables[0].Columns.Count; i++)
{
ws.Cell(str).Value = row[i].ToString();
ws.Cell(str).Style.Border.OutsideBorder = XLBorderStyleValues.Thin;
ws.Cell(str).Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Left);
b++;
str = b + "" + k;
}
k++;
}
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=Customer.xlsx");
}
catch { }
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
}
}
I had the same issue when exporting a GridView. I added a try/catch and exported the message to Excel and then realized that it was generating an error. I solved it thanks to the following answer: GridView must be placed inside a form tag with runat="server" even after the GridView is within a form tag
I am using Visual Studio 2015, Entity Framework 6 and C#.
I am trying to get my gridview to export to excel. I think I have everything, but when clicking the button my gridview disappears and nothing ever goes to a file.
My gridview is:
gvExOr
The Excel Export code is:
public partial class _Default : Page
{
private void BindFiles()
{
DirectoryInfo di = new DirectoryInfo(tbPath.Text);
gvExOr.DataSource = di.GetFiles();
try {
gvExOr.DataBind();
}
catch { }
}
protected void btnExportToExcel_Click(object sender, EventArgs e)
{
ExportToExcel();
}
//Export to Excel from a GridView
protected void ExportToExcel()
{
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application / vnd.ms - excel";
Response.AddHeader("content - disposition", "attachment; filename = MyFiles.xls");
Response.Charset = "";
this.EnableViewState = false;
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);
gvExOr.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
}
protected void Page_Load(object sender, EventArgs e)
{
BindFiles();
}
}
How do I get the gridview to export to excel?
Looks like you used code from this post https://stackoverflow.com/a/10412559/5786449
I tried the example from that post and it works for me. The only difference I can see is in your Response.ContentType and Response.AddHeader. Try getting rid of the white spaces in those parameters:
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("content-disposition", "attachment;filename=MyFiles.xls");
One more thing, your code doesn't actually give you an Excel spreadsheet. It just writes out the GridView HTML markup. Many Excel programs are not expecting HTML in an XLS file and will throw an error when opening the file. If you want an actual Excel spreadsheet I would recommend looking into utilities like EPPlus http://epplus.codeplex.com/
I have some radiobuttons on some tabs, when I click on one it generates an Excel-file.
<asp:RadioButton ID="rbAantallen1" runat="server" AutoPostBack="True"
GroupName="Soort" oncheckedchanged="rbRapport_CheckedChanged"
Text="Aantallen" />
The bug happens when I want to switch to the other tab. It keeps generating Excel-files. What can I do to stop running the checkedchanged event and SWITCH IN PEACE TO ANOTHER TAB?
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
MyDataSource.SelectCommand = #"
select melder_account,
aanvraag_titel,
fase_datum_opgelost_oplosser,
Melding_niveau_2,
rapporteren,
fase_datum_gestart,
fase_datum_opgelost,
doorlooptijd,
jurentkode
from uvw_HD_AANVRAAG_DOORLOOPTIJD_ALGEMEEN
where Melding_niveau_1 = 'Brandje'";
}
}
protected void MenuTabs_MenuItemClick(object sender, MenuEventArgs e)
{
int index = Int32.Parse(e.Item.Value);
multiTabs.ActiveViewIndex = index;
MyDataSource.SelectCommand = BepaalDataSource(index);
}
public string BepaalDataSource(int index)
{
string select = #"
select melder_account,
aanvraag_titel,
fase_datum_opgelost_oplosser,
Melding_niveau_2,
rapporteren,
fase_datum_gestart,
fase_datum_opgelost,
doorlooptijd,
jurentkode
from uvw_HD_AANVRAAG_DOORLOOPTIJD_ALGEMEEN
where Melding_niveau_1 = '";
if (index == 0)
{
cbPage.Checked = false;
return select += "Brandje'";
}
else
{
cbPage.Checked = true;
return select += "System - Netwerk'";
}
}
public DataView GetDataFromDataSource()
{
MyDataSource.SelectCommand = BepaalDataSource(Convert.ToInt16(cbPage.Checked));
return MyDataSource.Select(DataSourceSelectArguments.Empty) as DataView;
}
protected void rbRapport_CheckedChanged(object sender, EventArgs e)
{
DataTable dtOriginal = (DataTable)GetDataFromDataSource().ToTable(); //Return Table consisting data
DataTable dtTemp = new DataTable(); //Create Temporary Table
//Creating Header Row
dtTemp.Columns.Add("<b>Melder</b>");
dtTemp.Columns.Add("<b>Onderwerp</b>");
dtTemp.Columns.Add("<b>Oplosser</b>");
dtTemp.Columns.Add("<b>Niveau 2</b>");
dtTemp.Columns.Add("<b>Rapporteren</b>");
dtTemp.Columns.Add("<b>Gestart op</b>");
dtTemp.Columns.Add("<b>Opgelost op</b>");
dtTemp.Columns.Add("<b>Doorlooptijd</b>");
dtTemp.Columns.Add("<b>Jurentkode</b>");
DataRow drAddItem;
for (int i = 0; i < dtOriginal.Rows.Count; i++)
{
drAddItem = dtTemp.NewRow();
drAddItem[0] = dtOriginal.Rows[i][0].ToString();//Melder
drAddItem[1] = dtOriginal.Rows[i][1].ToString();//Onderwerp
drAddItem[2] = dtOriginal.Rows[i][2].ToString();//Oplosser
drAddItem[3] = dtOriginal.Rows[i][3].ToString();//Niveau 2
drAddItem[4] = dtOriginal.Rows[i][4].ToString();//Rapporteren
drAddItem[5] = dtOriginal.Rows[i][5].ToString();//Gestart op
drAddItem[6] = dtOriginal.Rows[i][6].ToString();//Opgelost op
drAddItem[7] = dtOriginal.Rows[i][7].ToString();//Doorlooptijd
drAddItem[8] = dtOriginal.Rows[i][8].ToString();//Jurentkode
dtTemp.Rows.Add(drAddItem);
}
DataGrid dg = new DataGrid(); //Temp Grid
dg.DataSource = dtTemp;
dg.DataBind();
ExportToExcel("Rapport.xls", dg);
dg = null;
dg.Dispose();
}
private void ExportToExcel(string strFileName, DataGrid dg)
{
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=" + strFileName);
Response.ContentType = "application/excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
dg.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
protected void cbRapport_CheckedChanged(object sender, EventArgs e)
{
}
A couple things come to mind.
In your rbRapport_CheckChanged() function you could check to make sure the radio button is visible.
You could also check your tab control to make sure you're on the right tab.
EDIT
Based on your comments, the hosting tab is invisible.
If that's the case, do something like this in your code
rbRapport_CheckChanged()
{
if(tab1.Visible == false)
return;
<rest of code here>
}
Where tab1 is the tab that rbRapport is on. This will check, if the tab isn't visible, you probably don't want to create an xls, so it will just short circuit and kick out of the event. If the tab is visible, it will process the event.
Edit
maybe you shouldn't be creating the xls when your radio button changes. Maybe you should have a button to click that says "Generate XLS" or something, and capture that click event. – taylonr Apr 28 at 11:42
Nothing wrong with the code provided. Please ensure that, you have not bind this rbRapport_CheckedChanged function with any other control's event like TabChangedEvent or CheckedChange event of other radio button which values will be changing based on tab change etc.
If not so, there may be problem with the parent controls of the RadioButton.