I have a GridView on a page. The user is able to input data in that GridView then I am downloading an Word file on Submit Event.
Now the question is: How can I download specific Column data to that word file? That word file also contains other data from different fields from same the page, which are working fine.
Below is the code for GridView: (Grid is binding on page load)
private void SetPreviousData()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
TextBox box1 = (TextBox)GridViewData11.Rows[rowIndex].Cells[1].FindControl("Data1");
TextBox box2 = (TextBox)GridViewData11.Rows[rowIndex].Cells[2].FindControl("Data2");
TextBox box3 = (TextBox)GridViewData11.Rows[rowIndex].Cells[3].FindControl("Data3");
TextBox box4 = (TextBox)GridViewData11.Rows[rowIndex].Cells[4].FindControl("Data4");
box1.Text = dt.Rows[i]["Column1"].ToString();
box2.Text = dt.Rows[i]["Column2"].ToString();
box3.Text = dt.Rows[i]["Column3"].ToString();
box4.Text = dt.Rows[i]["Column4"].ToString();
rowIndex++;
}
}
Below code is for Download data to Word file:
public void GenerateWordDoc()
{
string strBody = "<html>" +
"<body>" +
"<div> <b> Details </b></div> <br>" +
"<table MAX width=\"701\" height=\"646\" border=\"1\"> <tr><td width=\"191\" height=\"26\" >Name of user </td> <td height=\"86\" > Comments</td><td colspan=\"3\"> </td></tr> </table>" +
"</body>" +
"</html>";
string fileName = “wordfile.doc”;
Response.AppendHeader("Content-Type", "application/msword");
Response.AppendHeader("Content-disposition", "attachment; filename=" + fileName);
Response.Write(strBody);
}
Related
I read a few posts around here but couldn't find the answer so far.
I'm using the following code to export my GridView into Excel file:
protected void btnExportClick(object sender, EventArgs e)
{
StringBuilder builder = new StringBuilder();
string strFileName = "Report_" + DateTime.Now.ToShortDateString() + ".csv";
builder.Append("Firld1,Filed2,Field3,Field4,Field5" + Environment.NewLine);
foreach (GridViewRow row in gvMOSS2Merchants.Rows)
{
string f1= row.Cells[0].Text;
string f2= row.Cells[1].Text;
string f3= row.Cells[2].Text;
string f4= row.Cells[3].Text;
string f5= row.Cells[4].Text;
builder.Append(f1+ "," + f2+ "," + f3+ "," + f4+ "," + f5+ Environment.NewLine);
}
Response.Clear();
Response.ContentType = "text/cvs";
Response.AddHeader("Content-Disposition", "attachment;filename=" + strFileName);
Response.Write(builder.ToString());
Response.End();
}
When clicking on the button, the file is being created, but it has only headers and no data inside.
What can be wrong with that logic?
The following code works for me
this was called in button onclick event
OnClick="ExportExcel"
EXCEL EXPORT CODE
protected void ExportExcel(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=YourFileName" + DateTime.Now.ToString() + ".csv");
Response.Charset = "UTF8";
Response.ContentType = "application/text";
gridviewID.AllowPaging = false;
loadgrid();
StringBuilder sb = new StringBuilder();
for (int k = 0; k < gridviewID.Columns.Count; k++)
{
//add separator
sb.Append(gridviewID.Columns[k].HeaderText.ToString() + ',');
}
//append new line
sb.Append("\r\n");
for (int i = 0; i < gridviewID.Rows.Count; i++)
{
for (int k = 0; k < gridviewID.Columns.Count; k++)
{
//add separator
sb.Append(gridviewID.Rows[i].Cells[k].Text.Replace(",", " & ").Replace("\n", " ").Replace("\r", " ").ToString() + ',');
}
//append new line
sb.Append("\r\n");
}
Response.Output.Write(sb.ToString());
Response.Flush();
Response.End();
}
I have a GridView and a few columns are literal:
<asp:TemplateField HeaderText="Next Service Date">
<ItemTemplate>
<asp:Literal ID="litNextSvcDate" runat="server">/asp:Literal>
</ItemTemplate>
I want to convert this GridView to an Excel spreadsheet and all the boundfield columns display on the spreadsheet but not the literals. Here is the code to convert the Grid to Excel:
protected void ToExcel(GridView grid, string Name, string FileName)
{
if (!FileName.Contains(".xls"))
{
FileName = FileName + ".xls";
}
string style = "<style><!--table#page{mso-header-data:\"&C" + Name + " Date/: &D/ Page &P\"; mso-page-orientation:landscape; mso-page-scale:89;} br {mso-data-placement:same-cell;} --></style>";
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("content-disposition", "attachment; filename=" + FileName + "");
this.EnableViewState = false;
Response.Write("<html xmlns:x=\"urn:schemas-microsoft-com:office:excel\">");
Response.Write("<head>");
Response.Write(style);
Response.Write("<meta http-equiv=\"Content-Type\" content=\"text/html;charset=windows-1252\">");
Response.Write("<!--[if gte mso 9]>");
Response.Write("<xml>");
Response.Write("<x:ExcelWorkbook>");
Response.Write("<x:ExcelWorksheets>");
Response.Write("<x:ExcelWorksheet>");
Response.Write("<x:Name>" + Name + " Table</x:Name>");
Response.Write("<x:WorksheetOptions>");
Response.Write("<x:Panes>");
Response.Write("</x:Panes>");
Response.Write("<x:Print>");
Response.Write("<x:ValidPrinterInfo/>");
Response.Write("<x:Scale>89</x:Scale>");
Response.Write("</x:Print>");
Response.Write("</x:WorksheetOptions>");
Response.Write("</x:ExcelWorksheet>");
Response.Write("</x:ExcelWorksheets>");
Response.Write("</x:ExcelWorkbook>");
Response.Write("</xml>");
Response.Write("<![endif]-->");
Response.Write("</head>");
Response.Write("<body>");
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
List<int> HiddenCols = new List<int>();
for(int i = 0; i < grid.Columns.Count; i++)
{
if (!grid.Columns[i].Visible)
{
HiddenCols.Add(i);
}
}
for (int i = 0; i < grid.HeaderRow.Cells.Count; i++)
{
if(HiddenCols.Contains(i))
grid.HeaderRow.Cells[i].Visible = false;
}
ClearControls(grid);
grid.RenderBeginTag(oHtmlTextWriter);
grid.HeaderRow.RenderControl(oHtmlTextWriter);
foreach (GridViewRow row in grid.Rows)
{
for (int i = 0; i < row.Cells.Count; i++)
{
if (HiddenCols.Contains(i))
row.Cells[i].Visible = false;
}
row.RenderControl(oHtmlTextWriter);
}
grid.FooterRow.RenderControl(oHtmlTextWriter);
grid.RenderEndTag(oHtmlTextWriter);
Response.Write(oStringWriter.ToString());
Response.Write("</body>");
Response.Write("</html>");
Response.End();
}
Is there any way to automatically embed blob attachment into excel?
Header1 | Header2 | Header3 | Attachment
Record11 | Record12 | Record13| Blob data 1
My current method is output stream of text to a file in csv.
protected void btnExport_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition",
"attachment;filename=Report.csv");
Response.Charset = "";
Response.ContentType = "application/text";
StringBuilder sb = new StringBuilder();
for (int k = 0; k < grdReport.Columns.Count; k++)
{
sb.Append(grdReport.Columns[k].HeaderText + ',');
}
sb.Append("\r\n");
foreach (GridViewRow row in grdReport.Rows)
{
Label label1 = (Label)row.FindControl("lblCompany");
Label label2 = (Label)row.FindControl("lblDocNum");
Label label3 = (Label)row.FindControl("lblDocType");
string str = label1.Text + "," + label2.Text + "," + label3.Textt;
sb.Append(str);
sb.Append("\r\n");
}
Response.Output.Write(sb.ToString());
Response.Flush();
Response.End();
}
I have an ASP.Net 4.0 GridView and a button which exports the GridView data to Excel. This all works fine. However, within the GridView, the text in three cells of each row are red because they are hyperlinks. When I export the data to Excel, these cells are still red. I want them to be black. How do I do this? Here's my code:
Response.ClearContent();
Response.AppendHeader("content-disposition", "attachment; filename=Mobile.xls");
Response.ContentType = "application/excel";
StringWriter stringWriter = new StringWriter();
HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter);
foreach (GridViewRow gridViewRow in gvResults.Rows)
{
gridViewRow.ForeColor = Color.Black;
foreach (TableCell gridViewRowTableCell in gridViewRow.Cells)
gridViewRowTableCell.Style["forecolor"] = "#000000";
if (gridViewRow.RowType == DataControlRowType.DataRow)
{
for (int columnIndex = 0; columnIndex < gridViewRow.Cells.Count; columnIndex++)
{
gridViewRow.Cells[columnIndex].Attributes.Add("class", "text");
}
}
}
gvResults.RenderControl(htmlTextWriter);
string style = #"<style> .text { mso-number-format:\#; } </style> ";
Response.Write(style);
Response.Write(stringWriter.ToString());
Response.End();
And here's the code for the links. This runs OnDataBound:
foreach (GridViewRow row in gvResults.Rows)
{
if (row.RowType == DataControlRowType.DataRow || row.RowType == DataControlRowType.EmptyDataRow)
{
string imei = row.Cells[0].Text;
if (imei != " ")
{
string imeiLink = "window.location='SmartphoneInventory.aspx?imei=" + imei + "';";
row.Cells[0].Attributes.Add("onClick", String.Format(imeiLink));
row.Cells[0].Text = "<span style='color:red'>" + row.Cells[0].Text + "</span>";
}
string phonenumber = row.Cells[1].Text;
if (phonenumber != " ")
{
string phonenumberLink = "window.location='SmartphoneInventory.aspx?phonenumber=" + phonenumber + "';";
row.Cells[1].Attributes.Add("onClick", String.Format(phonenumberLink));
row.Cells[1].Text = "<span style='color:red'>" + row.Cells[1].Text + "</span>";
}
int cellCount = row.Cells.Count;
string empName = row.Cells[cellCount - 1].Text;
if (empName != " ")
{
string empNameLink = "window.location='DevicesByEmployee.aspx?empName=" + empName + "';";
row.Cells[cellCount - 1].Attributes.Add("onClick", String.Format(empNameLink));
row.Cells[cellCount - 1].Text = "<span style='color:red'>" + row.Cells[cellCount - 1].Text + "</span>";
}
}
}
I guess what I need is how to re-style the span. Is this possible? The GridView autogenerates its columns.
Get the LinkButton Text, assign it to the GridView Cell Text and Remove control.
Here is ho I do it in the header:
C#
foreach (TableCell c in gv.HeaderRow.Cells) {
if (c.HasControls) {
c.Text = (c.Controls(0) as LinkButton).Text;
c.Controls.Clear();
}
}
VB.NET
For Each c As TableCell In gv.HeaderRow.Cells
If c.HasControls Then
c.Text = TryCast(c.Controls(0), LinkButton).Text
c.Controls.Clear()
End If
Next
EDIT:
Create an extension method:
C#
[Extension()]
public string StripTags(string html)
{
return Regex.Replace(html, "<.*?>", "");
}
VB.NET
<Extension> _
Public Function StripTags(html As String) As String
Return Regex.Replace(html, "<.*?>", "")
End Function
It will remove tags from your string, therefore your style. Use as follows:
foreach (GridViewRow gridViewRow in gvResults.Rows)
{
gridViewRow.ForeColor = Color.Black;
foreach (TableCell gridViewRowTableCell in gridViewRow.Cells)
gridViewRowTableCell.Style["forecolor"] = "#000000";
if (gridViewRow.RowType == DataControlRowType.DataRow)
{
for (int columnIndex = 0; columnIndex < gridViewRow.Cells.Count; columnIndex++)
{
gridViewRow.Cells[columnIndex].Text = gridViewRow.Cells[columnIndex].Text.StripTags();
}
}
}
I have tried Exporting GridView to Excel but observed that
the Dynamically added last Row to Gridview is not exported to excel.
I have two datasets first one binds the data directly to Gridview.
After Which I add the last row from another DataSet.
In the page I'm able to see the result as Expected but when exported excel I'm not.
Below is my code:
DataSet dsgrid = SqlHelper.ExecuteDataset(DBConnectionString.ConnectionString, CommandType.StoredProcedure, "usp_Training_GetCirclescoreCardReport ", sqlparam);
if (TrainingUtil.isDataSetValid(dsgrid))
{
RSGScoreCard_Grid.DataSource = dsgrid;
RSGScoreCard_Grid.DataBind();
AddOverallRow(dsgrid);
}
else RSGScoreCard_Grid.DataBind();
Adding Overall row at bottom:
#region Add OverallRow
private void AddOverallRow(DataSet dsgrid)
{
using (GridViewRow gr = new GridViewRow(RSGScoreCard_Grid.Rows.Count + 1, 0, DataControlRowType.DataRow, DataControlRowState.Normal))
{
for (int i = 0; i < 6; i++)//6 is the column count for overall row
{
using (TableCell tc = new TableCell())
{
gr.Cells.Add(tc);
if (i == 0)
{
gr.Cells[i].ColumnSpan = 4;
gr.Cells[i].Text = "Overall";
gr.Cells[i].Attributes.Add("class", "fcol");
gr.Cells[i].Attributes.Add("style", "font-weight:bold;padding-left:20%");
}
else gr.Cells[i].Attributes.Add("style", "font-weight:bold");
}
}
if (dsgrid.Tables[1] != null)//creating a dynamic row to gridview
if (dsgrid.Tables[1].Rows.Count > 0)
{
gr.Cells[1].Text = dsgrid.Tables[1].Rows[0][5].ToString();
gr.Cells[1].Width = Unit.Percentage(8);
gr.Cells[2].Text = dsgrid.Tables[1].Rows[0][6].ToString();
gr.Cells[2].Width = Unit.Percentage(8);
gr.Cells[3].Text = dsgrid.Tables[1].Rows[0][7].ToString();
gr.Cells[3].Width = Unit.Percentage(8);
gr.Cells[4].Text = dsgrid.Tables[1].Rows[0][8].ToString();
gr.Cells[4].Width = Unit.Percentage(8);
gr.Cells[5].Text = dsgrid.Tables[1].Rows[0][9].ToString();
gr.Cells[5].Width = Unit.Percentage(8);
}
gr.Attributes.Add("class", "row2");
RSGScoreCard_Grid.Controls[0].Controls.AddAt(RSGScoreCard_Grid.Rows.Count + 1, gr);
}
}
#endregion
and Last my code to Export the GrieView:
protected void btnExport_Click(object sender, EventArgs e)
{
TrainingUtil.Export(ddlOptions.SelectedItem.Text.ToString().Replace(" ", string.Empty) + "_" + ddlVerticals.SelectedItem.Text.ToString().Replace(" ", string.Empty) + "_" + ddlLernerGroups.SelectedItem.Text.ToString().Replace(" ", string.Empty), RSGScoreCard_Grid, "For the Month/Year: " + ddlFromMonths.SelectedItem.Text.ToString()+"/"+ddlYears.SelectedItem.Text.ToString(), RSGScoreCard_Grid.HeaderRow.Cells.Count);
}
public override void VerifyRenderingInServerForm(Control control)
{
/* Confirms that an HtmlForm control is rendered for the specified ASP.NET
server control at run time. */
}
the Export Method in TrainingUtil class
#region Export
public static void Export(string filename, GridView grid, string Heading, int ColumnsCount)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", filename + ".xls"));
HttpContext.Current.Response.ContentType = "application/ms-excel";
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
grid.HeaderStyle.BackColor = System.Drawing.Color.Cyan;
//Cells color settings
GridViewRow row = new GridViewRow(0, 0, DataControlRowType.DataRow, DataControlRowState.Normal);
TableCell cell = new TableCell();
cell.Text = String.Format("{0}", Heading);
cell.ColumnSpan = ColumnsCount;
cell.Attributes.Add("align", "center");
cell.Attributes.Add("class", "yellow");
row.Cells.Add(cell);
grid.Controls[0].Controls.AddAt(0, row);
foreach (GridViewRow gridRow in grid.Rows)
{
foreach (TableCell tcGridCells in gridRow.Cells)
{
tcGridCells.Attributes.Add("class", "sborder");
}
}
grid.RenderControl(htw);
//Add the style sheet class here
HttpContext.Current.Response.Write(#"<style> .sborder { color : Black;border : 1px Solid Black; } .yellow {background-color:yellow;color:black;} </style> ");
HttpContext.Current.Response.Write(sw.ToString());
HttpContext.Current.Response.End();
}
}
}
#endregion
Can any help me out.Why I'm not able to export the last row.
Thanks in advance
I think in every post back your not binding the dynamically added rows.
Try to find the control which cause the postback and bind the data once again.
Code to find the postback control ex:-
public static Control GetPostBackControl(Page page)
{
Control control = null;
string ctrlname = page.Request.Params.Get("__EVENTTARGET");
if (ctrlname != null && ctrlname != string.Empty)
{
control = page.FindControl(ctrlname);
}
else
{
foreach (string ctl in page.Request.Form)
{
Control c = page.FindControl(ctl);
if (c is System.Web.UI.WebControls.Button)
{
control = c;
break;
}
}
}
return control;
}