How To exporting to Excel parent and nested GridView data? - c#

I have a gridview and some nested gridview inside it, when I try to export gridview data to Excel I get downloaded entire web page, I am sure it is beacause of nested gridviews.
How can I export parent and nested gridview data into an Excel sheet?
I use the following code to export to excel
gvExportToExcel.DataSource = objDs;
gvExportToExcel.DataBind();
System.Web.HttpContext curContext = System.Web.HttpContext.Current;
System.IO.StringWriter strWriter = null;
System.Web.UI.HtmlTextWriter htmlWriter = null;
curContext.Response.Clear();
curContext.Response.Buffer = true;
curContext.Response.AddHeader("content-disposition", "attachment; filename=" + System.Web.HttpUtility.UrlEncode("SearchSubmissionResult", System.Text.Encoding.UTF8) + ".xls");
curContext.Response.ContentType = "application/vnd.ms-excel";
curContext.Response.Write("<meta http-equiv=Content-Type content=text/html;charset=UTF-8>");
strWriter = new System.IO.StringWriter();
htmlWriter = new System.Web.UI.HtmlTextWriter(strWriter);
this.ClearControls(gvExportToExcel);
gvExportToExcel.RenderControl(htmlWriter);
curContext.Response.Write(strWriter.ToString());
curContext.Response.End();

Iterate the Rows collection of GridView and write the data to Excel file (via Oledb or Office InterOp).

Cleared this issue with following code.
//Clear the controls inside the parent grid-view before render.
gvExportToExcel.DataSource = objDs;
gvExportToExcel.DataBind();
System.Web.HttpContext curContext = System.Web.HttpContext.Current;
System.IO.StringWriter strWriter = null;
System.Web.UI.HtmlTextWriter htmlWriter = null;
curContext.Response.Clear();
curContext.Response.Buffer = true;
curContext.Response.AddHeader("content-disposition", "attachment; filename=" + System.Web.HttpUtility.UrlEncode("SearchSubmissionResult", System.Text.Encoding.UTF8) + ".xls");
curContext.Response.ContentType = "application/vnd.ms-excel";
curContext.Response.Write("<meta http-equiv=Content-Type content=text/html;charset=UTF-8>");
strWriter = new System.IO.StringWriter();
htmlWriter = new System.Web.UI.HtmlTextWriter(strWriter);
this.ClearControls(gvExportToExcel);
gvExportToExcel.RenderControl(htmlWriter);
curContext.Response.Write(strWriter.ToString());
curContext.Response.End();
//Clear method.
private void ClearControls(Control control)
{
try
{
for (int i = control.Controls.Count - 1; i >= 0; i--)
{
ClearControls(control.Controls[i]);
}
if (!(control is TableCell))
{
if (control.GetType().GetProperty("SelectedItem") != null)
{
LiteralControl literal = new LiteralControl();
control.Parent.Controls.Add(literal);
try
{
literal.Text = (string)control.GetType().GetProperty("SelectedItem").GetValue(control, null);
}
catch
{
}
control.Parent.Controls.Remove(control);
}
else
if (control.GetType().GetProperty("Text") != null)
{
LiteralControl literal = new LiteralControl();
control.Parent.Controls.Add(literal);
literal.Text = (string)control.GetType().GetProperty("Text").GetValue(control, null);
control.Parent.Controls.Remove(control);
}
}
}
catch (Exception ee)
{
lblError.Visible = true;
lblError.Text = ee.Message;
}
return;
}

Related

Export HTML string to Excel file in ASP.Net using C#

I have this table in database MySql version 8.0.17 which contains HTML code on field contents
<p><h3><span style=color:#0000ff;><strong>test</strong></span></h3></p>
<h4><strong>- test1</strong></h4>
<h4><strong>- test2</strong></h4>
I am not DB admin so I can only read from this table which i cannot modify..
when exporting this table in excel format on the xls file all HTML tags are found
How to do resolve this?
Thanks in advance for any help.
My code below
private void MTxlssp()
{
MySqlCommand cmd =
new MySqlCommand("SP");
DataTable dt = GetData(cmd);
GridView GridView1 = new GridView
{
AllowPaging = false,
DataSource = dt
};
GridView1.DataBind();
Thread.Sleep(3000);
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", attachment;filename=\"test.xls\"");
Response.ContentEncoding = Encoding.UTF8;
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
HttpCookie cookie2 = new HttpCookie("ExcelDownloadFlag")
{
Value = "Flag",
Expires = DateTime.Now.AddDays(1)
};
Response.AppendCookie(cookie2);
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.HeaderRow.BackColor = Color.White;
foreach (TableCell cell in GridView1.HeaderRow.Cells)
{
cell.BackColor = GridView1.HeaderStyle.BackColor;
}
foreach (GridViewRow row in GridView1.Rows)
{
row.BackColor = Color.White;
foreach (TableCell cell in row.Cells)
{
if (row.RowIndex % 2 == 0)
{
cell.BackColor = GridView1.AlternatingRowStyle.BackColor;
}
else
{
cell.BackColor = GridView1.RowStyle.BackColor;
}
cell.CssClass = "textmode";
}
}
GridView1.RenderControl(hw);
string style = #"<style> .textmode { } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
}
If its just the display text you need then maybe the library Nuglify will help you. It supports text extraction from HTML:
var html = #"<p><h3><span style=color:#0000ff;><strong>test</strong></span></h3></p>
<h4><strong>- test1</strong></h4>
<h4><strong>- test2</strong></h4>";
var result = Uglify.HtmlToText(html);
Console.WriteLine(result.Code);
You can download it from here: https://github.com/trullock/NUglify or get it from Nuget.
I have just run it on your html sample and it produces:
test - test1 - test2
I am assuming thats what you want based on your comment to #Ivan Khorin

how to create hyperlink programmatically in asp.net c# mvc 5 in excel sheet cell while export to excel using gridview

I want to create an hyperlink to a cell in Excel sheet while I am doing export to cell in C# MVC 5, I am using grid view to export to Excel.
I have used anchor tag to create link, when the files gets exported it read that field as string.
What is the other way to achieve this?
Below is what I have tried:
var result = from cssd in csdvm.FillControlStatusDetails.AsEnumerable()
select new
{
link = "<a href='www.google.com'> Link</a>
}
GridView gvExport = new GridView();
gvExport.AutoGenerateColumns = false;
BoundField nameColumn = new BoundField();
nameColumn.DataField = "link";
nameColumn.HeaderText = "Link";
gvExport.Columns.Add(nameColumn);
gvExport.DataSource = result.AsQueryable().ToList();
gvExport.DataBind();
gen.CreateExportHeaderRow(gvExport, "Control Status - Details");
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=ControlStatusDeatils-" + DateTime.Now.ToFileTimeUtc() + ".xls");
Response.ContentType = "application/vnd.xls";
Response.Charset = "";
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);
gvExport.RenderControl(htw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
Thank you i found the way out..i used a for loop to add the link below is what is did
for (int i = 0; i < gvExport.Rows.Count; i++)
var link = "<a href='" + gvExport.Rows[i].Cells[9].Text + "'>" + gvExport.Rows[i].Cells[10].Text+ "</a>" + "<br/>";
}
gvExport.Rows[i].Cells[9].Text = MvcHtmlString.Create(link).ToHtmlString();
using above code i am able to give an hyper link to an Excel cell while i am doing export to excel

Export nested Gridview blank cell error

I followed this guide : Export Multi-Level Nested GridView to Excel using OpenXml in ASP.Net
And modified the code for my case as follows:
protected void ExportExcel(object sender, EventArgs e)
{
var dt = new DataTable("GridView_Data");
grvPayroll.AllowPaging = false;
var grvPayrollDetails = new GridView();
for (var i = 0; i < grvPayroll.Rows.Count; i++)
{
grvPayrollDetails = (GridView) grvPayroll.Rows[i].FindControl("grvPayrollDetails");
grvPayrollDetails.AllowPaging = false;
}
foreach (TableCell cell in grvPayrollDetails.HeaderRow.Cells)
{
if (cell.Text != " ")
{
dt.Columns.Add(cell.Text);
}
}
foreach (GridViewRow row in grvPayroll.Rows)
{
var grvPayrollDetailscell = (row.FindControl("grvPayrollDetails") as GridView);
for (var j = 0; j < grvPayrollDetailscell.Rows.Count; j++)
{
dt.Rows.Add(row.Cells[1].Text, row.Cells[2].Text, grvPayrollDetailscell.Rows[j].Cells[1].Text,
grvPayrollDetailscell.Rows[j].Cells[2].Text);
}
}
using (var wb = new XLWorkbook())
{
wb.Worksheets.Add(dt);
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=GridView.xlsx");
using (var MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
}
}
No error occurred, but the export file just contain the header , all cells are empty. The export excel file with exactly the header name and the number of rows. Why? Please help!
Here is the picture:
Exported File

I want to export data to PDF/Excel

I want export data to Excel, for that I have use the code (linked below), code is working, data is being exported, but Excel is not downloading, please anyone can help me what is the problem?
Export data into Excel, Word and PDF with Formatting
This how I have use this code in my project
foreach (var enq_item in enquiries)
{
enquiry_list.Add(new enquiry_master
{
enquiry_source_id = enq_item.enquiry_source_id,
reference_no = enq_item.reference_no,
assigned_staff_no = enq_item.assigned_staff_no,
emp_id = enq_item.emp_id,
status_id = enq_item.status_id,
remarks = enq_item.remarks,
system_date_time = enq_item.system_date_time,
name = enq_item.name,
departing_from = enq_item.departing_from,
travelling_to = enq_item.travelling_to,
departing_date = enq_item.departing_date,
returning_date = enq_item.returning_date,
mobile_no = enq_item.mobile_no,
email = enq_item.email,
}
}
//Get the data from database into datatable
DataTable dt = ToDataTable(enquiry_list);
//Create a dummy GridView
GridView GridView1 = new GridView();
GridView1.AllowPaging = false;
GridView1.DataSource = dt;
GridView1.DataBind();
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=DataTable.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
string filename = "DownloadTest.xls";
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
for (int i = 0; i < GridView1.Rows.Count; i++)
{
//Apply text style to each Row
GridView1.Rows[i].Attributes.Add("class", "textmode");
}
GridView1.RenderControl(hw);
//style to format numbers to string
string style = #"<style> .textmode { mso-number-format:\#; } </style>";
Response.Write(style);
Response.Write(hw.ToString());
Response.End();
Actually our requirement was need to export data to Excel or PDF then we realize best is PDF according to over requirements so I tried ItextSharp it's work out to me this my code
public string generatePDF()
{
string HTML = ""; ///Create a html as per our need
HTML += "<html>";
///Update the html here
HTML += "</html>";
string pdf_file_path = Request.PhysicalApplicationPath + "pdf\\quotations\\"; //getting physical application path for save the pdf
string final_name = "Here pdf name";
PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream(pdf_file_path + final_name, FileMode.Create));
wri.PageEvent = new ITextEvents();
doc.Open();
var content = wri.DirectContent;
content.MoveTo(28, doc.PageSize.Height - 150);
content.LineTo(28, doc.PageSize.Height - 200);
content.Stroke(); //generating line
content.MoveTo(573, doc.PageSize.Height - 150);
content.LineTo(573, doc.PageSize.Height - 200);
content.Stroke();
HTMLWorker htmlworker = new HTMLWorker(doc); //here we have to pass created instance of pdfWritter
htmlworker.SetStyleSheet(style);
htmlworker.Parse(new StringReader(HTML)); ///here pass the created HTML what we have need in the PDF
doc.NewPage();
doc.Close();
var json = JsonConvert.SerializeObject(final_name, Newtonsoft.Json.Formatting.Indented, common.JsonSerializeSettings());
return json; // retruning the file name
Response.Write(doc);
Response.End();
}
Above code is worked to me. Finally I'm returning the file name and showing the PDF in browser using the JavaScript

How do I replace the checkboxes in my C# excel export to ones and zeros?

In a C# application I created a GridView dynamically and exported it to Excel. The issue that I am having is that since three fields are Bit columns in SQL they export as checkboxes and not ones and zeros. I have done some searching on google for similar issues and found this article this solution. However, this will not work out since right or left clicking on the object only checks or unchecks the box.
I have also tried to find information on how to export the bit fields as 1's and 0's from C# and have not been able to find anything. Here is my export script:
StringWriter writer = new StringWriter();
HtmlTextWriter htmlWriter = new HtmlTextWriter(writer);
GridView gridView = new GridView();
gridView.DataSource = sdsResults;
gridView.AutoGenerateColumns = true;
gridView.DataBind();
gridView.HeaderRow.Style.Add("background-color", "#003c74");
gridView.HeaderRow.Style.Add("color", "#ffffff");
for (int i = 0; i < gridView.Rows.Count; i++)
{
GridViewRow row = gridView.Rows[i];
//Change Color back to white
row.BackColor = System.Drawing.Color.White;
//Apply text style to each Row
row.Attributes.Add("class", "textmode");
//Apply style to Individual Cells of Alternating Row
if (i % 2 != 0)
{
row.BackColor = System.Drawing.Color.AliceBlue;
}
foreach(TableCell cell in row.Cells)
{
if(cell.HasControls() == true)
{
if(cell.Controls[0].GetType().ToString() == "System.Web.Ui.WebControls.CheckBox")
{
CheckBox chk = (CheckBox)cell.Controls[0];
if(chk.Checked)
{
cell.Text = "1";
}
else
{
cell.Text = "0";
}
}
}
}
}
gridView.RenderControl(htmlWriter);
htmlWriter.Close();
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=myfile.xls");
Response.Charset = "";
Response.Write(writer.ToString());
Response.End();
Response.End();
in the for loop, you can do something like this:
foreach(TableCell cell in row.Cells)
{
if(cell.HasControls() == true)
{
if(cell.Controls[0].GetType().ToString() == "System.Web.UI.WebControls.CheckBox")
{
CheckBox chk = (CheckBox)cell.Controls[0];
if(chk.Checked)
{
cell.Text = "1";
}
else{
cell.Text = "0";
}
}
}
}
If you're building the datasource with a SQL query then CAST the bit columns as int or varchar. If that can't be done try defining the GridView columns with desired data types before assigning the datasource.
protected void btnXlsExport_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
gvStandard.AllowPaging = false;
gvStandard.DataBind();
for (int i = 0; i <= gvStandard.Rows.Count - 1; i++) {
GridViewRow row = gvStandard.Rows(i);
foreach (TableCell cell in row.Cells) {
if (cell.HasControls() == true) {
if (cell.Controls(0).GetType().ToString() == "System.Web.UI.WebControls.CheckBox") {
CheckBox chk = (CheckBox)cell.Controls(0);
if (chk.Checked) {
cell.Text = "True";
} else {
cell.Text = "False";
}
}
}
}
}
gvStandard.HeaderRow.Style.Add("background-color", "#FFFFFF");
gvStandard.RenderControl(hw);
Response.Output.Write(sw);
Response.Flush();
Response.End();
}
Protected Sub btnXlsExport_Click(sender As Object, e As EventArgs) Handles btnXlsExport.Click
Response.Clear()
Response.Buffer = True
Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls")
Response.Charset = ""
Response.ContentType = "application/vnd.ms-excel"
Dim sw As New StringWriter()
Dim hw As New HtmlTextWriter(sw)
gvStandard.AllowPaging = False
gvStandard.DataBind()
For i As Integer = 0 To gvStandard.Rows.Count - 1
Dim row As GridViewRow = gvStandard.Rows(i)
For Each cell As TableCell In row.Cells
If cell.HasControls() = True Then
If cell.Controls(0).[GetType]().ToString() = "System.Web.UI.WebControls.CheckBox" Then
Dim chk As CheckBox = DirectCast(cell.Controls(0), CheckBox)
If chk.Checked Then
cell.Text = "True"
Else
cell.Text = "False"
End If
End If
End If
Next
Next
gvStandard.HeaderRow.Style.Add("background-color", "#FFFFFF")
gvStandard.RenderControl(hw)
Response.Output.Write(sw)
Response.Flush()
Response.End()
End Sub

Categories