I use this code to export datagridview to excel
HtmlForm form = new HtmlForm();
Response.Clear();
Response.Buffer = true;
string fileName = "TRAIL" + "[" + DatefromTxtBox.Text.Replace("/", "") + "_" + DatetoTxtBox.Text.Replace("/", "") + "]" + ".xls";
Response.AddHeader("content-disposition", "attachment;filename=" + fileName);
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
AuditTrailGV.AllowPaging = false;
AuditTrailGV.DataSource = (DataSet)ViewState["audit"];
AuditTrailGV.DataBind();
form.Controls.Add(AuditTrailGV);
this.Controls.Add(form);
form.RenderControl(hw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
the problem is this code also catches the formatting/borders of my gridview
here are the sample screen shots
This is my gridview in asp.net
and this is what appears in my excell
as you can see it transformed all of the lines like the gridview, i do not want it to happen, as much as possible if i can only retain the gridlines for the rows with data only, if its not possible, remove all the gridlines..
any help? i really do not like those gridlines in my excell
VB
Public Overrides Sub VerifyRenderingInServerForm(control As Control)
'base.VerifyRenderingInServerForm(control);
'This remains empty
End Sub
Protected Sub btnExcel_Click(sender As Object, e As ImageClickEventArgs) Handles btnExcel.Click
Response.Clear()
Response.AddHeader("content-disposition", "attachment;filename=FileName.xls")
Response.Charset = ""
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.ContentType = "application/vnd.ms-excel"
Dim stringWrite As New System.IO.StringWriter()
Dim htmlWrite As System.Web.UI.HtmlTextWriter = New HtmlTextWriter(stringWrite)
htmlWrite.Write("<html xmlns:o=""urn:schemas-microsoft-com:office:office"" ")
htmlWrite.Write("xmlns:x=""urn:schemas-microsoft-com:office:excel"" ")
htmlWrite.Write("xmlns=""http://www.w3.org/TR/REC-html40""> ")
htmlWrite.Write("<head> ")
htmlWrite.Write("<!--[if gte mso 9]><xml> ")
htmlWrite.Write("<x:ExcelWorkbook> ")
htmlWrite.Write("<x:ExcelWorksheets> ")
htmlWrite.Write("<x:ExcelWorksheet> ")
htmlWrite.Write("<x:Name>Sheet1</x:Name> ")
htmlWrite.Write("<x:WorksheetOptions> ")
htmlWrite.Write("<x:Selected/> ")
htmlWrite.Write("<x:ProtectContents>False</x:ProtectContents> ")
htmlWrite.Write("<x:ProtectObjects>False</x:ProtectObjects> ")
htmlWrite.Write("<x:ProtectScenarios>False</x:ProtectScenarios> ")
htmlWrite.Write("</x:WorksheetOptions> ")
htmlWrite.Write("</x:ExcelWorksheet> ")
htmlWrite.Write("</x:ExcelWorksheets> ")
htmlWrite.Write("</x:ExcelWorkbook> ")
htmlWrite.Write("</xml><![endif]--> ")
htmlWrite.Write("</head>")
htmlWrite.WriteLine("")
gridView.HeaderStyle.Reset()
gridView.FooterStyle.Reset()
gridView.AlternatingRowStyle.Reset()
gridView.RowStyle.Reset()
gridView.BackColor = Color.Transparent
gridView.GridLines = GridLines.None
gridView.RenderControl(htmlWrite)
Response.Write(stringWrite.ToString())
Response.[End]()
End Sub
C#
public override void VerifyRenderingInServerForm(Control control)
{
//base.VerifyRenderingInServerForm(control);
//This remains empty
}
protected void btnExcel_Click(object sender, ImageClickEventArgs e)
{
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=FileName.xls");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.ms-excel";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
htmlWrite.Write("<html xmlns:o=\"urn:schemas-microsoft-com:office:office\" ");
htmlWrite.Write("xmlns:x=\"urn:schemas-microsoft-com:office:excel\" ");
htmlWrite.Write("xmlns=\"http://www.w3.org/TR/REC-html40\"> ");
htmlWrite.Write("<head> ");
htmlWrite.Write("<!--[if gte mso 9]><xml> ");
htmlWrite.Write("<x:ExcelWorkbook> ");
htmlWrite.Write("<x:ExcelWorksheets> ");
htmlWrite.Write("<x:ExcelWorksheet> ");
htmlWrite.Write("<x:Name>Sheet1</x:Name> ");
htmlWrite.Write("<x:WorksheetOptions> ");
htmlWrite.Write("<x:Selected/> ");
htmlWrite.Write("<x:ProtectContents>False</x:ProtectContents> ");
htmlWrite.Write("<x:ProtectObjects>False</x:ProtectObjects> ");
htmlWrite.Write("<x:ProtectScenarios>False</x:ProtectScenarios> ");
htmlWrite.Write("</x:WorksheetOptions> ");
htmlWrite.Write("</x:ExcelWorksheet> ");
htmlWrite.Write("</x:ExcelWorksheets> ");
htmlWrite.Write("</x:ExcelWorkbook> ");
htmlWrite.Write("</xml><![endif]--> ");
htmlWrite.Write("</head>");
htmlWrite.WriteLine("");
gridView.HeaderStyle.Reset();
gridView.FooterStyle.Reset();
gridView.AlternatingRowStyle.Reset();
gridView.RowStyle.Reset();
gridView.BackColor = Color.Transparent;
gridView.GridLines = GridLines.None;
gridView.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}
You can try below code and custom the color of the downloaded data. It will also not color the Column and rows other then the data.
protected void DownloadExcel_Click(object sender, EventArgs e)
{
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Report.xls"));
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
GridView1.AllowPaging = false;
GridView1.DataBind();
GridView1.HeaderRow.Style.Add("background-color", "#FFFFFF");
for (int i = 0; i < GridView1.HeaderRow.Cells.Count; i++)
{
GridView1.HeaderRow.Cells[i].Style.Add("background-color", "#bfc2c7");
}
int j = 1;
foreach (GridViewRow gvrow in GridView1.Rows)
{
//gvrow.BackColor = color.White;
if (j <= GridView1.Rows.Count)
{
if (j % 2 != 0)
{
for (int k = 0; k < gvrow.Cells.Count; k++)
{
gvrow.Cells[k].Style.Add("background-color", "#EFF3FB");
}
}
}
j++;
}
GridView1.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
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 want export data from DataTable into excel file using Response.Write.
However some of the data missing from the excel file. Can help me fix this.
I already try create html using StringBuilder and nothing wrong with the loop, can get all the data, only when export to excel it's missing. Please help me with this.
Response.Buffer = true;
Response.ClearContent();
Response.Write(HEADER);
Response.Write(STYLE);
Response.Write("</head><body><table border=\"0\" style=\"font-size:11pt\"><tr>");
Response.AddHeader("content-disposition", attachment);
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
Response.Write(strTitle);
Response.Write("</tr>");
Response.Write("<tr><td colspan=3>From Date: " + lblFromDate.Text + " To: " + lblToDate.Text + "</td></tr>");
Response.Write("<tr><td colspan=9>Protocol: " + lblProtocol.Text + "</td></tr>");
Response.Write("<tr><td colspan=9>Production Line: " + lblPL.Text + "</td></tr>");
Response.Write("<tr></tr></table>");
Response.Write("<table border=\"1\" style=\"font-size:11pt\">");
Response.Write("<tr>");
for (int i = 0; i < summaryreporttable.Columns.Count - 2; i++)
{
Response.Write(" <th>" + summaryreporttable.Columns[i].ToString() + "</th>");
}
Response.Write("</tr>");
for (int r = 0; r < summaryreporttable.Rows.Count; r++)
{
Response.Write("<tr>");
Response.Write("<td>"+r+"</td>");
for (int i = 0; i < summaryreporttable.Columns.Count - 2; i++)
{
if (summaryreporttable.Columns[i].ToString() == "Issue Date")
{
//Response.Write("<td class=\"x167\" valign=\"top\">" + summaryreporttable.Rows[r][i] + "</td>");
Response.Write(String.Format("<td class=\"x167\" valign=\"top\"> {0} </td>", summaryreporttable.Rows[r][i]));
}
else
{
//Response.Write("<td class=\"x169\" valign=\"top\">" + summaryreporttable.Rows[r][i] + "</td>");
Response.Write(String.Format("<td class=\"x169\" valign=\"top\"> {0} </td>", summaryreporttable.Rows[r][i]));
}
}
Response.Write("</tr>");
Response.Flush();
}
Response.Write("</table></body></html>");
}
catch (Exception ex)
{
}
finally
{
Response.End();
}
As you can see, the data between is missing.
I want to explain our way. This is usefull then yours.
1-we have a literal in the web page like this
<asp:Literal ID="lblData" runat="server" />
2-In the code we have some string variables. And we grow with html like drawing on a screen.
// our html datas
// you can use foreach for repating
sTEXT = #"<table class='table'><thead>";
sTEXT += #"<th>";
sTEXT += #"Caption A";
sTEXT += #"</th>";
sTEXT += #"</thead>";
sTEXT += #"<tr>";
sTEXT += #"<td>abcdef</td>";
sTEXT += #"<td>ghjklm</td>";
sTEXT += #"</tr>";
sTEXT += #"</table>";
// our screen literaldata sets
lblData.Text = sTEXT;
// excel output code
// carefull end of the "Responce.Write"" sentence
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1254");
Response.Charset = "windows-1254";
Response.AppendHeader("content-disposition", "attachment;filename=ExportedHtml.xls");
Response.Buffer = true;
this.EnableViewState = false;
Response.ContentType = "application/vnd.ms-excel";
Response.Write("<style> TABLE { border: 1px solid gray; } TD { border: 1px solid gray; } </style> " + lblData.Text);
Response.End();
I Have A gridView with data contain Arabic letters On My website When I Export To Csv File
on localhost It works Fine when i purplish on server the Arabic letters appear like ????????
where the problem
this is my code
protected void btn_SaveCSV_Click(object sender, EventArgs e)
{
// Response.Clear();
HttpContext.Current.Response.Clear();
Response.Write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />");
Response.Buffer = true;
Response.AddHeader("content-disposition",
"attachment;filename=GridViewExport.csv");
Response.Charset = "";
//Response.ContentType = "application/text";
Response.ContentType = "text/csv; charset-UTF-8";
Response.ContentEncoding = System.Text.Encoding.Default;
Grid_offlineMessages.AllowPaging = false;
FillGrid();
StringBuilder sb = new StringBuilder();
for (int k = 0; k < Grid_offlineMessages.Columns.Count; k++)
{
//add separator
sb.Append(Grid_offlineMessages.Columns[k].HeaderText + ',');
}
//append new line
sb.Append("\r\n");
for (int i = 0; i < Grid_offlineMessages.Rows.Count; i++)
{
for (int k = 0; k < Grid_offlineMessages.Columns.Count; k++)
{
//add separator
sb.Append(Grid_offlineMessages.Rows[i].Cells[k].Text + ',');
}
//append new line
sb.Append("\r\n");
}
Response.Output.Write(sb.ToString());
Response.Flush();
Response.End();
}
Try setting the encoding to UTF-8 like this:
Response.ContentEncoding = System.Text.Encoding.UTF8;