When saving html table as excel is giving error? - c#

TableRow tr = new TableRow();
TableCell yrs = new TableCell();
yrs.BorderWidth = 1;
yrs.BorderColor = System.Drawing.Color.Black;
yrs.Text = year.Substring(4);
tr.Cells.Add(yrs);
TableCell fname = new TableCell();
fname.BorderWidth = 1;
fname.BorderColor = System.Drawing.Color.Black;
fname.Text = test;
tr.Cells.Add(fname);
TableCell lname = new TableCell();
lname.BorderWidth = 1;
lname.BorderColor = System.Drawing.Color.Black;
lname.Text = test1.ToString();
tr.Cells.Add(lname);
TABULAR.Rows.Add(tr);
Response.Write(TABULAR);
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=test123.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter swWriter = new StringWriter();
HtmlTextWriter htwWriter = new HtmlTextWriter(swWriter);
TABULAR.RenderControl(htwWriter);
Response.Write(swWriter.ToString());
Response.End();

The problem here is you're dealing with a Table object which specifically:
Displays a table on a Web page.
and does not in any way represent an Excel 'table' or anything else.
Claiming it is an Excel file by modifying the response headers only tricks the browser, you do not have a valid Excel file

Related

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

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

Remove first row contents in excel while export to excel

I'm using the below code to export the gridview to excel. When I export the contents are appearing fine with no problems, but I am getting a control label like System.WebControls.UI.Style this in my first cell in A1 cell.
Is there a way to hide this or remove and below is my code.
CS:
protected void Unnamed1_Click(object sender, ImageClickEventArgs e)
{
// ExportToExcel();
if (ViewState["DashboardDetails"] != null)
{
lblError.Text = string.Empty;
lblError.Style.Add("display", "None");
grdHorizontalSeatDashboard.AllowPaging = false;
DataTable dtHorizontalDashboard = (DataTable)ViewState["DashboardDetails"];
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=HorizontalDashboard.xls");
Response.Charset = "utf-8";
Response.ContentType = "application/vnd.ms-excel";
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter hw = new HtmlTextWriter(sw);
grdHorizontalSeatDashboard.AllowPaging = false;
grdHorizontalSeatDashboard.DataSource = (DataTable)ViewState["DashboardDetails"];
grdHorizontalSeatDashboard.DataBind();
grdHorizontalSeatDashboard.HeaderRow.BackColor = Color.White;
//Horizontal Cell
TableCell cell0 = grdHorizontalSeatDashboard.HeaderRow.Cells[0];
cell0.BackColor = ColorTranslator.FromHtml("#9AD6EE");
cell0.Width = grdHorizontalSeatDashboard.HeaderRow.Cells[0].Width;
TableCell cell1 = grdHorizontalSeatDashboard.HeaderRow.Cells[1];
cell1.BackColor = ColorTranslator.FromHtml("#96B060");
cell1.Width = grdHorizontalSeatDashboard.HeaderRow.Cells[1].Width;
TableCell cell2 = grdHorizontalSeatDashboard.HeaderRow.Cells[2];
cell2.BackColor = ColorTranslator.FromHtml("#96B060");
cell2.Width = grdHorizontalSeatDashboard.HeaderRow.Cells[2].Width;
TableCell cell3 = grdHorizontalSeatDashboard.HeaderRow.Cells[3];
cell3.BackColor = ColorTranslator.FromHtml("#96B060");
cell3.Width = Unit.Pixel(100);
TableCell cell4 = grdHorizontalSeatDashboard.HeaderRow.Cells[4];
cell4.BackColor = ColorTranslator.FromHtml("#C57838");
cell4.Width = grdHorizontalSeatDashboard.HeaderRow.Cells[4].Width;
TableCell cell5 = grdHorizontalSeatDashboard.HeaderRow.Cells[5];
cell5.BackColor = ColorTranslator.FromHtml("#C57838");
cell5.Width = grdHorizontalSeatDashboard.HeaderRow.Cells[5].Width;
TableCell cell6 = grdHorizontalSeatDashboard.HeaderRow.Cells[6];
cell6.BackColor = ColorTranslator.FromHtml("#C57838");
cell6.Width = grdHorizontalSeatDashboard.HeaderRow.Cells[6].Width;
// Likely $ Impact & Overall Horizontal Utilization
TableCell cell10 = grdHorizontalSeatDashboard.HeaderRow.Cells[10];
cell10.BackColor = ColorTranslator.FromHtml("#9AD6EE");
cell10.Width = grdHorizontalSeatDashboard.HeaderRow.Cells[10].Width;
TableCell cell11 = grdHorizontalSeatDashboard.HeaderRow.Cells[11];
cell11.BackColor = ColorTranslator.FromHtml("#9AD6EE");
cell11.Width = grdHorizontalSeatDashboard.HeaderRow.Cells[11].Width;
foreach (GridViewRow row in grdHorizontalSeatDashboard.Rows)
{
foreach (TableCell cell in row.Cells)
{
cell.BackColor = row.BackColor;
cell.HorizontalAlign = HorizontalAlign.Center;
cell.CssClass = "textmode";
}
}
foreach (TableCell cell in grdHorizontalSeatDashboard.FooterRow.Cells)
{
cell.BackColor = grdHorizontalSeatDashboard.FooterRow.BackColor;
cell.HorizontalAlign = HorizontalAlign.Center;
}
Style style = new Style();
style.BackColor = Color.White;
Response.Write(style);
grdHorizontalSeatDashboard.RenderControl(hw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
}
}
To hide the first column or the first row (A1), just count the current row/column iteration and intercept the first and hide the A1 cell.
var rowCounter = 0;
var cellCounter = 0;
foreach (GridViewRow row in grdHorizontalSeatDashboard.Rows)
{
foreach (TableCell cell in row.Cells)
{
if (rowCounter == 0 && cellCounter == 0)
{
cell.Text = "";
}
cell.BackColor = row.BackColor;
cell.HorizontalAlign = HorizontalAlign.Center;
cell.CssClass = "textmode";
}
cellCounter = 0;
rowCounter++;
}

Execute codes after Response.End()

Im having trouble executing codes after Response.End().
Im using this to export a datatable/ASP Table to MS Excel(.xls).
The export finishes but my Gridview is not loading anymore. The command that I use to load the gridview is written after Response.End().
I tried using HttpContext.Current.ApplicationInstance.CompleteRequest(); but it did not help.
I tried also Response.Redirect("Charges_Trs.aspx", false); still did not work..
Any help please..Here is my code
lblNotif.Text = "Selected items have been posted. Exporting XLS ... (will be saved in your desktop)";
exportToExcel(dt); //calls the function to export the datatable to excel, i passed dt=datatable to this function
timerNotif.Enabled = true;
btnSearch_Click(null, null); //called the event of a button that loads the gridview
here is the function exporttoexcel()
public void exportToExcel(DataTable dt)
{
Table dTable = new Table();
TableRow dTableRow = new TableRow();
//Column Headings
for (int i = 0; i < dt.Columns.Count; i++)
{
TableCell tCell = new TableCell();
tCell.Text = dt.Columns[i].ToString();
dTableRow.Cells.Add(tCell);
}
dTable.Rows.Add(dTableRow);
//Rows
for (int i = 0; i < dt.Rows.Count; i++)
{
dTableRow = new TableRow();
for (int j = 0; j < dt.Columns.Count; j++)
{
TableCell tCell = new TableCell();
dTableRow.Cells.Add(tCell);
}
dTable.Rows.Add(dTableRow);
}
if (Response.IsClientConnected)
{
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=PostedCharges" + DateTime.Now.ToString("MMddyyyy") + ".xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
dTable.RenderControl(hw);
string style = #"<style> .textmode { mso-number-format:\#; } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
}
can u try adding the code in the btnSearch click event(hope it is to bind the grid with some data ) after calling export, instead of calling that click event.

export to excel using asp date issue

Hi there i have this code to export my data gridview to excel
and my problem is that, the gridview shows a 12hr format but when i export it to excel it shows a 24hr format, how ca i make it into 12 hr format? thank you.
DataSet ds = (DataSet)ViewState["audit"];
DataTable dt = new DataTable();
dt = ds.Tables[0];
Table table = new Table();
AuditTrailGV.AllowPaging = false;
AuditTrailGV.DataSource = (DataSet)ViewState["audit"];
AuditTrailGV.DataBind();
for (int i = 0; i < AuditTrailGV.HeaderRow.Cells.Count; i++)
{
AuditTrailGV.HeaderRow.Cells[i].Style.Add("background-color", "#bfc2c7");
}
AuditTrailGV.HeaderRow.Style.Add("border-color", "#FFFFFF");
int j = 1;
foreach (GridViewRow gvrow in AuditTrailGV.Rows)
{
//gvrow.BackColor = color.White;
gvrow.Style.Add("background-color", "#FFFFFF");
gvrow.Style.Add("border-color", "#bfc2c7");
if (j <= AuditTrailGV.Rows.Count)
{
if (j % 2 != 0)
{
for (int k = 0; k < gvrow.Cells.Count; k++)
{
gvrow.Cells[k].Style.Add("background-color", "#EFF3FB");
gvrow.Cells[k].Style.Add("border-color", "#bfc2c7");
}
}
else
{
for (int k = 0; k < gvrow.Cells.Count; k++)
{
gvrow.Cells[k].Style.Add("border-color", "#bfc2c7");
}
}
}
j++;
}
foreach (GridViewRow row in AuditTrailGV.Rows)
{
table.Rows.Add(row);
}
TableHeaderCell header = new TableHeaderCell();
header.RowSpan = 1;
header.ColumnSpan = 6;
header.Text = "Inventory Accounting and Control System";
header.Font.Bold = true;
header.HorizontalAlign = HorizontalAlign.Center;
header.VerticalAlign = VerticalAlign.Middle;
header.Font.Size = 20;
TableRow headerrow = new TableRow();
headerrow.Cells.Add(header);
TableHeaderCell header2 = new TableHeaderCell();
header2.RowSpan = 1;
header2.ColumnSpan = 6;
header2.Text = "Audit Trail";
header2.Font.Bold = true;
header2.HorizontalAlign = HorizontalAlign.Center;
header2.VerticalAlign = VerticalAlign.Middle;
header2.Font.Size = 16;
TableRow headerrow2 = new TableRow();
headerrow2.Cells.Add(header2);
TableHeaderCell header3 = new TableHeaderCell();
header3.RowSpan = 1;
header3.ColumnSpan = 6;
header3.Text = DatefromTxtBox.Text + " to " + DatetoTxtBox.Text;
header3.Font.Bold = true;
header3.HorizontalAlign = HorizontalAlign.Center;
header3.VerticalAlign = VerticalAlign.Middle;
header3.Font.Size = 16;
TableRow headerrow3 = new TableRow();
headerrow3.Cells.Add(header3);
table.Rows.AddAt(0, headerrow);
table.Rows.AddAt(1, headerrow2);
table.Rows.AddAt(2, headerrow3);
table.Rows.AddAt(3, AuditTrailGV.HeaderRow);
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "IACSAuditTrail" + "[" + DatefromTxtBox.Text.Replace("/", "") + "_" + DatetoTxtBox.Text.Replace("/", "") + "]" + ".xls"));
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
table.RenderControl(htw);
Response.Write(sw.ToString());
Response.End()
This it what it looks
but this is what i looks when i export it to excel :(
The only way to save date format is to pre-format the date field as text and then export to excel. To do this,
string style = #"<style> TD { mso-number-format:\#; } </style> ";
Response.write(style);
//Code to Export Control
Panel1.RenderControl(htmlWrite);
you can refer to below link for more information
http://www.aspsnippets.com/Articles/Export-GridView-To-Word-Excel-PDF-CSV-Formats-in-ASP.Net.aspx

Categories