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
Related
I have a small web application that creates two datatables from a jquery datepicker. I am able to export those datatables to excel of course if they are on the same page.
I've changed my application to render the datatables on new webforms.
Here is my code to export to excel:
protected void ExportToExcel(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";
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter hw = new HtmlTextWriter(sw);
//To Export all pages
this.BindGrid1(TextDateFrom.Text, TextDateTo.Text);
GridView2.HeaderRow.BackColor = Color.White;
foreach (TableCell cell in GridView2.HeaderRow.Cells)
{
cell.BackColor = GridView2.HeaderStyle.BackColor;
}
foreach (GridViewRow row in GridView2.Rows)
{
row.BackColor = Color.White;
foreach (TableCell cell in row.Cells)
{
if (row.RowIndex % 2 == 0)
{
cell.BackColor = GridView2.AlternatingRowStyle.BackColor;
}
else
{
cell.BackColor = GridView2.RowStyle.BackColor;
}
cell.CssClass = "textmode";
}
}
GridView2.RenderControl(hw);
//style to format numbers to string
string style = #"<style> .textmode { } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
}
Here is where I am having trouble:
this.BindGrid1(TextDateFrom.Text, TextDateTo.Text);
Of course my BindGrid1() is an another form. To call my datatables in my new forms I created a session.
If I have the code on the web form where the data tables are:
DataTable dt = (DataTable)Session["GridData"];
if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
I'm not sure exactly how to call that this. to export all pages. Should I have created a global variable that takes the String values from the BindGrid1 method to then use on the new page?
Pertinent to your task, the data export from DataTable dt to Excel can be achieved using the following procedure, which utilizes Microsoft.Office.Interop.Excel object library:
/// <summary>
/// export DataTable to Excel (C#)
/// </summary>
internal static void Export2Excel(DataTable dataTable)
{
object misValue = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Excel.Application _appExcel = null;
Microsoft.Office.Interop.Excel.Workbook _excelWorkbook = null;
Microsoft.Office.Interop.Excel.Worksheet _excelWorksheet = null;
try
{
// excel app object
_appExcel = new Microsoft.Office.Interop.Excel.Application();
// excel workbook object added to app
_excelWorkbook = _appExcel.Workbooks.Add(misValue);
_excelWorksheet = _appExcel.ActiveWorkbook.ActiveSheet as Microsoft.Office.Interop.Excel.Worksheet;
// column names row (range obj)
Microsoft.Office.Interop.Excel.Range _columnsNameRange;
_columnsNameRange = _excelWorksheet.get_Range("A1", misValue).get_Resize(1, dataTable.Columns.Count);
// column names array to be assigned to _columnNameRange
string[] _arrColumnNames = new string[dataTable.Columns.Count];
for (int i = 0; i < dataTable.Columns.Count; i++)
{
// array of column names
_arrColumnNames[i] = dataTable.Columns[i].ColumnName;
}
// assign array to column headers range, make 'em bold
_columnsNameRange.set_Value(misValue, _arrColumnNames);
_columnsNameRange.Font.Bold = true;
// populate data content row by row
for (int Idx = 0; Idx < dataTable.Rows.Count; Idx++)
{
_excelWorksheet.Range["A2"].Offset[Idx].Resize[1, dataTable.Columns.Count].Value =
dataTable.Rows[Idx].ItemArray;
}
// Autofit all Columns in the range
_columnsNameRange.Columns.EntireColumn.AutoFit();
}
catch { throw; }
}
just pass dt as an argument.
Hope this may help.
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 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
I am working on a web page which has a gridview control. I need the data to be transferred to .xls format. I am able to create the .xls file and transfer the data, but the problem is that I need the gridcells to be displayed in the background in the excel sheet. Right now, it is only showing a blank background without the gridcells. Otherwise the gridview is getting transferred fine. Due to this issue, printing the .xls file is a problem. Tables with more columns are not compressing, but getting printed over 2-3 pages. My code is as follows:
public static void ExportToXLS(string fileName, GridView gv,string companyName,string reportTitle , string period)
{
//For writing to XLS file
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", fileName));
HttpContext.Current.Response.ContentType = "application/ms-excel";
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
Table tableReport = new Table();
tableReport.GridLines = gv.GridLines;
// add the header row to the table
if (gv.HeaderRow != null)
{
ReportList.PrepareControlForExport(gv.HeaderRow);
tableReport.Rows.Add(gv.HeaderRow);
}
// add each of the data rows to the table
foreach (GridViewRow row in gv.Rows)
{
ReportList.PrepareControlForExport(row);
tableReport.Rows.Add(row);
}
// add the footer row to the table
if (gv.FooterRow != null)
{
ReportList.PrepareControlForExport(gv.FooterRow);
tableReport.Rows.Add(gv.FooterRow);
}
//Takes value of company name
System.Web.UI.WebControls.Label labelCompany = new System.Web.UI.WebControls.Label();
labelCompany.Text = companyName;
labelCompany.Font.Bold = true;
//Takes value of report title
System.Web.UI.WebControls.Label labelReport = new System.Web.UI.WebControls.Label();
labelReport.Text = reportTitle;
labelReport.Font.Bold = true;
//Takes value of report period
System.Web.UI.WebControls.Label labelPeriod = new System.Web.UI.WebControls.Label();
labelPeriod.Text = period;
// render the htmlwriter into the response
htw.Write("<center>");
labelCompany.RenderControl(htw);
htw.Write("<br/>");
labelReport.RenderControl(htw);
htw.Write("<br/>");
labelPeriod.RenderControl(htw);
htw.Write("</center>");
htw.Write("<br/>");
tableReport.RenderControl(htw);
HttpContext.Current.Response.Write(sw.ToString());
HttpContext.Current.Response.End();
}
}
}
Any suggestions?
Ref: Export grid
Try this:
protected void btnExportExcel_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);
grdExport.AllowPaging = false;
oMailing.GetData(out ODs);
grdExport.DataSource = ODs;
grdExport.DataBind();
//Change the Header Row back to white color
grdExport.HeaderRow.Style.Add("background-color", "#FFFFFF");
//Apply style to Individual Cells
grdExport.HeaderRow.Cells[0].Style.Add("background-color", "green");
grdExport.HeaderRow.Cells[1].Style.Add("background-color", "green");
grdExport.HeaderRow.Cells[2].Style.Add("background-color", "green");
grdExport.HeaderRow.Cells[3].Style.Add("background-color", "green");
grdExport.HeaderRow.Cells[4].Style.Add("background-color", "green");
grdExport.RenderControl(hw);
//style to format numbers to string
string style = #"<style> .textmode { mso-number-format:\#; } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
All of the answers will get you what you want - you're just missing the formatting part.
At the end of the day, what you are really creating is an HTML file (with an HTML Table) that Excel can read. The RESPONSE headers in #BhaskarreddyMule is what "forces" the client to treat the file as an "xls" file and if it has Excel run and open it (but the bottom line is that its not really a "native" Excel file.
Now that's out of the way, think in HTML. Style your columns, rows, and text content as you would in HTML. That's how you'd control the format (i.e. old school "nowrap" to prevent wrapping cell content, font-size, etc. etc.).
I haven't done this in a while (I've moved on to Excel XML and VB.Net XML literals when I need to do this) so I'm not sure how much level of control you have with RenderControl...or if you have to go even further "old school" and build the HTML table string from scratch.....
First of all Refer this: How to export nested gridview to excel/word with gridlines on the child grid, Hope it will help you to solve your problem.
Ref: How to export gridview to excel in a console type application?
You can refer to the Export To Excel control in the below link. It’s a custom control. Hope it can help you.
http://exporttoexcel.codeplex.com/
Styling exported grid:
protected void btnExportExcel_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);
grdExport.AllowPaging = false;
oMailing.GetData(out ODs);
grdExport.DataSource = ODs;
grdExport.DataBind();
//Change the Header Row back to white color
grdExport.HeaderRow.Style.Add("background-color", "#FFFFFF");
//Apply style to Individual Cells
grdExport.HeaderRow.Cells[0].Style.Add("background-color", "green");
grdExport.HeaderRow.Cells[1].Style.Add("background-color", "green");
grdExport.HeaderRow.Cells[2].Style.Add("background-color", "green");
grdExport.HeaderRow.Cells[3].Style.Add("background-color", "green");
grdExport.HeaderRow.Cells[4].Style.Add("background-color", "green");
for (int i = 0; i < grdExport.Rows.Count; i++)
{
GridViewRow row = grdExport.Rows;
//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.Cells[0].Style.Add("background-color", "#C2D69B");
row.Cells[1].Style.Add("background-color", "#C2D69B");
row.Cells[2].Style.Add("background-color", "#C2D69B");
row.Cells[3].Style.Add("background-color", "#C2D69B");
row.Cells[4].Style.Add("background-color", "#C2D69B");
}
}
grdExport.RenderControl(hw);
//style to format numbers to string
string style = #"<style> .textmode { mso-number-format:\#; } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
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);
I tried with the export to excel, seems that you first need to create an using part Excel = using Microsoft.Office.Interop.Excel, when u click on the button, just create an excel class having workbook and worksheet property and then using gridview property of Gridview.Row[].cell[].Text., u can dynamically store every value in the gridview to the worksheet and then write it to a FILE....
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;
}