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
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
Haven't found any good solution to export a GridView to Excel with following options :
Page orientation set to Landscape
Margins Normal
All columns fit to one page
Existing code to export to Excel is as follows
private void ExportToExcel(GridView grdGridView)
{
DataTable dt = Whatever();
grdGridView.AllowPaging = false;
grdGridView.Columns[13].Visible = false;
grdGridView.DataSource = dt;
grdGridView.DataBind();
string attachment = "attachment; filename=ExcelSheet1.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
HtmlForm frm = new HtmlForm(); // Create a form to contain the grid
grdGridView.Parent.Controls.Add(frm);
frm.Attributes["runat"] = "server";
frm.Controls.Add(grdGridView);
frm.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
}
What could be the best possible way to export to Excel in order to achieve all of this? Do I need to use some library or some other tool like report viewer? Is it possible or not?
Found the solution
Download epplus library.
using OfficeOpenXml;
private void ExportToExcel()
{
using (ExcelPackage objExcelPackage = new ExcelPackage())
{
//Create the worksheet
ExcelWorksheet objWorksheet = objExcelPackage.Workbook.Worksheets.Add("ExcelSheet1");
DataTable dtQuoteComparison = dt //Load the datatable into the sheet, starting from cell A1. Print the column names on row 1
objWorksheet.Cells["A1"].LoadFromDataTable(dt, true);
var start = objWorksheet.Dimension.Start;
var end = objWorksheet.Dimension.End;
for (int row = start.Row+1; row <= end.Row; row++) //iterate through rows
{
objWorksheet.Cells[rowStart, colStart, rowEnd,colEnd].WhateverProperty=value;
}
objWorksheet.PrinterSettings.Orientation = eOrientation.Landscape;
objWorksheet.PrinterSettings.FitToWidth = 1;
//Write it back to the client
if (System.IO.File.Exists(filepath))
System.IO.File.Delete(filepath);
//Create excel file on physical disk
FileStream objFileStrm = System.IO.File.Create(filepath);
objFileStrm.Close();
//Write content to excel file
System.IO.File.WriteAllBytes(filepath,objExcelPackage.GetAsByteArray());
}
}
Now the problem I am facing is that All columns fit to one page is not working even after setting
objWorksheet.PrinterSettings.FitToWidth = 1;
I am new to asp.net and need to create a project. My requirement is I have a table where I will store data. This is my main table. Under each id I have a separate table:
Msg_id Src Dest
701 RADAR MSC
702 MSC RADAR
Msg_id Message_size Mgs_desc
701 256 PFM_Load
Like that it continues... I have 3 dropdown lists. The 1st one is msg_id, the 2nd is src and the 3rd is dest. I also have a submit button the user can select any one of the dropdown lists and the corresponding table should be displayed in MS-Word.
You will need to create report of this data in .NET
Use EnableRenderExtension( "HTML4.0", "MS Word" ); for this purpose.
Then will have to export that report into word file.
Follow link:
http://www.codeproject.com/Articles/35225/Advanced-Report-Viewer
Or
Step by Step Approach:
http://www.accelebrate.com/sql_training/ssrs_2008_tutorial.htm
Hope Its helpful.
u can use this:
THis code for export into csv formate which can open in both msword&msexcel:
private void OutPutFileToCsv(DataTable dt, string fileName, string seperator)
{
StringWriter stringWriter = new StringWriter();
Int32 iColCount = dt.Columns.Count;
for (Int16 i = 0; i < iColCount; i++)
{
stringWriter.Write(dt.Columns[i]);
if (i < iColCount - 1)
{
if (seperator.Contains(";"))
stringWriter.Write(";");
else
stringWriter.Write(",");
}
}
stringWriter.Write(stringWriter.NewLine);
foreach (DataRow dr in dt.Rows)
{
for (int i = 0; i < iColCount; i++)
{
if (!Convert.IsDBNull(dr[i]))
{
stringWriter.Write(dr[i].ToString().Trim());
}
if (i < iColCount - 1)
{
if (seperator.Contains(";"))
stringWriter.Write(";");
else
stringWriter.Write(",");
}
}
stringWriter.Write(stringWriter.NewLine);
}
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "text/csv";
Response.AddHeader("Content-Disposition", String.Format("attachment; filename={0}", fileName));
Response.ContentEncoding = Encoding.GetEncoding("iso-8859-1");
//Response.BinaryWrite(Encoding.Unicode.GetPreamble());
Response.Write(stringWriter.ToString());
Response.End();
}
just pass your datatable in function and get grid data in ms-word.
private void ExportToWord(DataTable dt)
{
if (dt.Rows.Count > 0)
{
string filename = "DownloadReport.xls";
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
DataGrid dgGrid = new DataGrid();
dgGrid.DataSource = dt;
dgGrid.DataBind();
//Get the HTML for the control.
dgGrid.RenderControl(hw);
//Write the HTML back to the browser.
Response.ContentType = "application/msword";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");
this.EnableViewState = false;
Response.Write(tw.ToString());
Response.End();
}
}
Hope it helps you.
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....