export data grid view into excel in asp dot net - c#

export data grid view to excel code is run and all data export into excel sheet but i want to only selected column in excel sheet how to solve this problem
protected void btnexcel_Click1(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition",
"attachment;filename=ActualsAndBudgets.xls");
Response.Charset = "";
Response.ContentType = "application/ms-excel";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gvdetails.AllowPaging = false;
fillgrid();
gvdetails.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
gvdetails.AllowPaging = true;
fillgrid();
}
public override void VerifyRenderingInServerForm(Control control)
{
}

using System;
using System.Data;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Whatever
{
///
/// This class provides a method to write a dataset to the HttpResponse as
/// an excel file.
///
public class ExcelExport
{
public static void ExportDataSetToExcel(DataSet ds, string filename)
{
HttpResponse response = HttpContext.Current.Response;
// first let's clean up the response.object
response.Clear();
response.Charset = "";
// set the response mime type for excel
response.ContentType = "application/vnd.ms-excel";
response.AddHeader("Content-Disposition", "attachment;
filename=\"" + filename + "\"");
// create a string writer
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
// instantiate a datagrid
DataGrid dg = new DataGrid();
dg.DataSource = ds.Tables[0];
dg.DataBind();
dg.RenderControl(htw);
response.Write(sw.ToString());
response.End();
}
}
}
}
}

Related

Exporting Gridview to .xls but excel file is not generating

I have written the below code to generate the excel file.
private void ExportReport(IList ApproveListData, string fileName)
{
var gv = new GridView();
gv.AllowPaging = false;
gv.DataSource = ApproveListData;
gv.DataBind();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
Response.ContentType = "application/ms-excel";
Response.Charset = "";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gv.RenderControl(htw);
Response.Output.Write("<b> Pending approval report </b>");
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
I have checked data in the grid view but excel file is not generating.
Please help.
Thanks in advance.

How to download SQL data in excel format using asp.net

I'm trying to download my data in excel format . Following code does the work perfectly but format comes out to be corrupted.
Error which I get - The file format and extension don't match. The file could be corrupted or unsafe. Unless you trust its source, don't open it. Do you want to open it anyways?
On confirming Yes, file opens.
Please have to look at the code and help me understand what change I must make to download my data in (xls 97-2003 excel workbook).
if (dt4.Rows.Count > 0)
{
string filename = "DownloadMobileNoExcel.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 = dt4;
dgGrid.DataBind();
//Get the HTML for the control.
dgGrid.RenderControl(hw);
//Write the HTML back to the browser.
//Response.ContentType = application/vnd.ms-excel;
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");
this.EnableViewState = false;
Response.Write(tw.ToString());
Firstly
Download Open Xml
Download Close Xml Library
import this Namespaces
using System.IO;
using System.Data;
using ClosedXML.Excel;
using System.Configuration;
using System.Data.SqlClient;
try to do that like this
using (XLWorkbook wb = new XLWorkbook())
{
wb.Worksheets.Add(dt, "Customers");
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=SqlExport.xlsx");
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
}
Mudassar Khan has a nice article regarding that
here

could not generate excel file on button click in c#

In my project when i click on a button it should generate excel file and in the middle of first line in excel file as a heading i should get as "my first excel file". I could not get it when i am trying with following code.Any ideas?. Thanks in advance
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
namespace listofdirectories
{
public partial class ExportToExcel : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
HttpResponse response = HttpContext.Current.Response;
response.ContentType = "application/ms-excel";
response.AddHeader("Content-Disposition", "attachment;filename=practise.xls");
StreamWriter stw = new StreamWriter();
HtmlTextWriter htw = new HtmlTextWriter(stw);
stw.WriteLine("my first excel file");
response.End();
}
}
}
You forgot to add the content to the response like this-
response.Write(stw.ToString());
response.End();
Also change your content type to this -
response.ContentType = "application/vnd.ms-excel";
Instead of using StreamWriter use StringWriter and change your code like this-
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.Charset = "";
string FileName = "filename.xls";
StringWriter strwritter = new StringWriter();
HtmlTextWriter htmltextwrtter = new HtmlTextWriter(strwritter);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType ="application/vnd.ms-excel";
Response.AddHeader("Content-Disposition","attachment;filename=" + FileName);
Response.Write(strwritter.ToString());
Response.End();
To load the content in to the excel file, if recommend that you load the dataset with the data, then bind a grid view with that dataset and render the gridview as html after that fill the response with that rendered html like this-
GridView gv = new GridView();
gv.DataSource = dataset; //Your datasource from database
gv.DataBind();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=filename.xls");
Response.ContentType = "application/vnd.ms-excel";
Response.Charset = "";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gv.RenderControl(htw);
Response.Write(sw.ToString());
Response.Flush();
Response.End();

Export to excel using asp.net

I am using following function to export my data to excel sheet:
string filename = "Test.xls";
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
//Get the H`enter code here`TML for the control.
yourGrid.RenderControl(hw);
//Write the HTML back to the browser.
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");
Response.Write(tw.ToString());
but excel sheet is not created. Although it shows in chrome browser bottom that excel is downloading. When it finishs downloading, I click it and it says file cant be opened. Please suggest me what is wrong in it?
[EDIT]
Response.Clear();
Response.Buffer = true;
//use Response.AddHeader
Response.AddHeader("content-disposition", "attachment;filename=Test.xlsx");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
gvLogs.RenderControl(hw);
gvLogs.AllowPaging = false;
gvLogs.DataBind(); // bind data
Response.Output.Write(sw.ToString());
//need to call Flush and End methods
Response.Flush();
Response.End();
give same error
Epplus is a good library for excel import/export. You can check it out.
You can try this one
private void ExportToExcel(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/vnd.ms-excel";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");
this.EnableViewState = false;
Response.Write(tw.ToString());
Response.End();
}
}
Change the 'Response.ContentType' value in your code as like below.
Response.ContentType = "application/vnd.xls";
Hope this will help you.
check below code
Response.Clear();
Response.Buffer = true;
//use Response.AddHeader
Response.AddHeader("content-disposition", "attachment;filename=Test.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.xls";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.RenderControl(hw);
GridView1.AllowPaging = false;
GridView1.DataBind(); // bind data
Response.Output.Write(sw.ToString());
//need to call Flush and End methods
Response.Flush();
Response.End();

Converting aspx to pdf

I have use ItextSharp to generate pdf file from an aspx page.
But it gives me an error in an obj.Parse(se), where se is the string reader and it takes the path of:-
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
I am stuck with this problem.
Please help and give suggesstion.
Thank You
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text.RegularExpressions;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using iTextSharp.text.xml;
using System.Xml;
using iTextSharp.text.html.simpleparser;
public partial class Pdf : System.Web.UI.Page
{
protected override void Render(HtmlTextWriter writer)
{
MemoryStream mem = new MemoryStream();
StreamWriter twr = new StreamWriter(mem);
HtmlTextWriter myWriter = new HtmlTextWriter(twr);
base.Render(myWriter);
myWriter.Flush();
myWriter.Dispose();
StreamReader strmRdr = new StreamReader(mem);
strmRdr.BaseStream.Position = 0;
string pageContent = strmRdr.ReadToEnd();
strmRdr.Dispose();
mem.Dispose();
writer.Write(pageContent);
CreatePDFDocument(pageContent);
}
public void CreatePDFDocument(string strHtml)
{
string strFileName = HttpContext.Current.Server.MapPath("test.pdf");
// step 1: creation of a document-object
Document document = new Document();
// step 2:
// we create a writer that listens to the document
PdfWriter.GetInstance(document, new FileStream(strFileName, FileMode.Create));
StringReader se = new StringReader(strHtml);
HTMLWorker obj = new HTMLWorker(document);
document.Open();
obj.Parse(se);
document.Close();
ShowPdf(strFileName);
}
public void ShowPdf(string strFileName)
{
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("Content-Disposition", "inline;filename=" + strFileName);
Response.ContentType = "application/pdf";
Response.WriteFile(strFileName);
Response.Flush();
Response.Clear();
}
}
Here is an example that worked for me. There is a bit of code but it shows ways you can take advantage of things like css. Hope it helps.
private void ExportToPDF()
{
string s = "<table><td><tr>First<b>row</b></tr></td></table>";
Document document = new Document(PageSize.LETTER, 30, 30, 60, 35);
MemoryStream msReport = new MemoryStream();
string strHTMLpath = Server.MapPath("../myHTML.html");
string strPDFpath = Server.MapPath("../myPDF.pdf");
try
{
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
StreamWriter strWriter = new StreamWriter(strHTMLpath, false, Encoding.UTF8);
strWriter.Write(s.ToString());
strWriter.Close();
strWriter.Dispose();
iTextSharp.text.html.simpleparser.StyleSheet styles = new iTextSharp.text.html.simpleparser.StyleSheet();
styles.LoadTagStyle("ol", "leading", "16,0");
PdfWriter.GetInstance(document, new FileStream(strPDFpath, FileMode.Create));
document.Add(new Header(iTextSharp.text.html.Markup.HTML_ATTR_STYLESHEET, "Style.css"));
document.Open();
ArrayList objects;
styles.LoadTagStyle("li", "face", "garamond");
styles.LoadTagStyle("span", "size", "8px");
styles.LoadTagStyle("body", "font-family", "times new roman");
styles.LoadTagStyle("body", "font-size", "10px");
document.NewPage();
objects = iTextSharp.text.html.simpleparser.
HTMLWorker.ParseToList(new StreamReader(strHTMLpath, Encoding.Default), styles);
for (int k = 0; k < objects.Count; k++)
{
document.Add((IElement)objects[k]);
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
document.Close();
Response.Write(strPDFpath);
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("Content-Disposition", "attachment; filename=myFileName.pdf");
Response.ContentType = "application/octet-stream";
Response.WriteFile(strPDFpath);
Response.Flush();
Response.Close();
File.Delete(strPDFpath);
}
}

Categories