exporting sql query result to excel - asp.net

In my asp.net application i wanted to export the SQL query result to Excel and that excel should be avaliable to the user as a download.
Please help

I find working with excel to be a real headache, but it's possible to do just about anything if you want to. What features do you need to leverage, because offering a csv file instead is much easier!
Do you have SSRS, you could offer the query as an SSRS report and it is automatically available as an excel download!

If your on MS SQL Server, reporting services are available for free and can do this for you easily, you can also export to PDF and Word.
If not, or if its just a one off try here

you can show your result in a datagrid. after that you can export this grid to excel file.
do like this :
I pass grid by session.
Control grdList;
GridView grdList1 = Session["GridView"] as GridView;
if (grdList1 == null)
{
grdList = (DataGrid)Session["GridView"];
}
else
{
grdList = (GridView)Session["GridView"];
}
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=ExportList.xls");
Response.Charset = "";
// If you want the option to open the Excel file without saving than
// comment out the line below
// Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.xls";
Response.ContentEncoding = System.Text.Encoding.UTF8;// GetEncoding(1256);// UTF8;
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite =
new HtmlTextWriter(stringWrite);
grdList.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();

Related

Exporting gridview to microsoft powerpoint in c#

I want to export gridview to powerpoint.I have the following code.But I have the following problems:
when I am using it for ms office 2010.its giving error:
Powerpoint cannot read c:\users\filename.ppt. The presentation cannot
be opened. Your antivirus program may prevent you from opening the
presentation. To fix this problem, make sure your antivirus program is
current and working correctly. If the problem persists and the
presentation is from someone that you trust, turn off your antivirus
program, and then try to open the presentation again. If you do this,
make sure you turn on your antivirus program again after you open the
presentation.
when I am using it for ms office 2007,its opening but there is no gridview
CODE:
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=FileName.ppt");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Charset = "";
// this.Response.ContentType = "application/vnd.openxmlformats- officedocument.presentationml.presentation";
this.Response.ContentType = "application/vnd.ms-powerpoint.presentation.macroEnabled.12";
this.Response.ContentType = "application/vnd.ms-powerpoint";
//Response.ContentType = "application/vnd.ppt";
GridView2.AllowPaging = false;
GridView2.DataBind();
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
GridView2.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
Response.Flush();
Try to use an external library to generate your ppt or pptx.
Like aspose.net or Open xml.

Export Repeater to MS Word and SAVE the Word file on Server or Database C#, ASP.NET

I have a situation where I have to generate a MS Word report by exporting the Repeater to Word Document. I am doing it but my requirement is to Save the MS Word file either on Server / Database. How can I save that file on Server/Database after generating the Word Document?
Requirement is to Generate and Save the Word file on either Server / Database and also the generated or saved file should be a Read-Only file. How can I do it ?
Here is the Code I am using to generate Word file..
protected void DisplayRepeater()
{
if (ddlDivRAHQ.SelectedValue == "DIV")
{
Repeater_PrintFinalReport.DataSource = new ReportItems().Get_Rpt_Items_Div_Chief(Convert.ToInt32(Session["UserNumber"]), DateTime.Parse(Session["ReportStartDate"].ToString()), DateTime.Parse(Session["ReportEndDate"].ToString()), ddlDivRAHQ.SelectedValue.ToString()).OrderBy(x => x.OrgNum).ThenBy(x => x.Office_Location).ThenBy(x => x.Site_Desc).ToList();
}
else
{
Repeater_PrintFinalReport.DataSource = new ReportItems().Get_Rpt_Items_Div_Chief(Convert.ToInt32(Session["UserNumber"]), DateTime.Parse(Session["ReportStartDate"].ToString()), DateTime.Parse(Session["ReportEndDate"].ToString()), ddlDivRAHQ.SelectedValue.ToString()).Where(x=>x.Finalized == 1).OrderBy(x => x.Site_Desc).ToList();
}
Repeater_PrintFinalReport.DataBind();
Repeater_PrintFinalReport.Visible = true;
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=" + ddlDivRAHQ.SelectedValue + "_WeeklyReport_" + DateTime.Now.ToShortDateString() + ".doc");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.word";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
Repeater_PrintFinalReport.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}
I have taken the help from the below link
http://support.microsoft.com/kb/316384
MS.Word using Microsoft.Office.Interop.Word
How to automate Microsoft Word to create a new document by using Visual C#

ASP.Net page export to pdf

I got stuck with my ASP.Net export to PDF. Below are my codes. Please help.
Response.Clear();
Response.Buffer = true;
Response.Charset = Encoding.UTF8.HeaderName;
Response.ContentEncoding = Encoding.UTF8;
Response.Write(string.Format("<meta http-equiv=Content-Type content=text/html;charset={0}>", Encoding.UTF8.HeaderName));
Response.ContentType = "application/pdf";
Response.Headers.Add("Content-disposition", "attachment; filename=pdffilename.pdf");
StringBuilder sb = new StringBuilder();
sb.Append("MIME-Version: 1.0\r\n");
sb.Append("X-Document-Type: Worksheet\r\n");
sb.Append("Content-Type: multipart/related; boundary=\"----=mtrSystem\"\r\n\r\n\r\n");
sb.Append("------=mtrSystem\r\n");
sb.Append("Content-Type: text/html; charset=\"utf-8\"\r\n");
sb.Append("<html xmlns:o=\"urn:schemas-microsoft-com:office:office\"\r\n");
sb.Append("xmlns:x=\"urn:schemas-microsoft-com:office:pdf\">\r\n\r\n\r\n");
sb.Append("------=mtrSystem\r\n");
sb.Append("Content-ID: baiduimg\r\n");
sb.Append("Content-Transfer-Encoding: base64\r\n");
sb.Append("Content-Type: image/png\r\n\r\n");
Can i use this way to export my ASP.Net page to PDF?
Html-to-pdf.net allows for converting html to pdf. TO get the html from an asp.net page, use the following code:
StringWriter sw = new StringWriter();
Server.Execute("PageToConvert.aspx", sw);
string htmlCodeToConvert = sw.GetStringBuilder().ToString();
Then pass the html to the pdf generator:
public byte[] GetPdfBytesFromHtmlString (string htmlString)
You can then save the bytes to the response to send to client, or save on the server as a local file.
EDIT:
Something to keep in mind, html-to-pdf does cost money, but for my last project it was a justified expense. You can use the trial version to figure out what you needd.
I'm not entirely sure what you're trying to do, but generally I can highly recommend PDFSharp for creating PDF documents in code...

Export a data set to Excel and raise a file download dialog from an asp.net web method

I am using the following code to export a data set to an Excel sheet.
[WebMethod]
public static void ExporttoExcel()
{
DataSet ds;
productfactory pf=new productfactory();
ds = pf.getproducts();
HttpResponse response = HttpContext.Current.Response;
// first let's clean up the response.object
response.Clear();
response.Charset = "";
response.ContentEncoding = System.Text.Encoding.Default;
// set the response mime type for excel
response.ContentType = "application/vnd.ms-excel";
response.AddHeader("Content-Disposition", "attachment;filename=\"products.xls\"");
// 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);
string filepath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\products.xls";
response.Write(sw.ToString());
// response.End();
}
}
}
The problem is that it's not raising file download and hence no export is taking place. The same code works fine in a normal method. But with the web method it's not working.
I suggest to make an HttpHandler ending in ashx, and place inside him your code that create the excel file.
then call it from your javascript code like that.
document.location.href = "ExporttoExcel.ashx";
The problem is that WebMethods are not designed to allow you to interact with the Response object (evident in that it wasn't available and you had to use HttpContext.Current.Response to get to it). WebMethods are designed to be blackbox to the user. They will perform and action and/or return a value.
Perhaps you can give us a better idea of what you are trying to accomplish and we can suggest an alternate solution.
u can use to create a dynamic iframe with URL set to the Web Handler to generate the Excel this will raise the file download with out posting the current page.

Export Gridview with image to Excel - Problem

I have a Gridview in my ASP.NET C# Page. It has a couple of columns and also one image column. I can export the entire columns to an Excel file, but the image column is blank. By the way, I use the full path.
Any Idea?
Yes in default.aspx (For local Export)
ImageUrl="http://localhost:4056/CSharp/banner.gif"
instead of ImageUrl="~/banner.gif"
or (For remote Export)
http://your ip address here :port/foldername/filename
Response.Clear(); //this clears the Response of any headers or previous output
Response.Buffer = true; //make sure that the entire output is rendered simultaneously
Response.ContentType = "application/vnd.ms-excel";
StringWriter stringWriter = new StringWriter(); //System.IO namespace should be used
HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter);
GridView2.GridLines = GridLines.Both;
GridView2.RenderControl(htmlTextWriter);
Response.Write(stringWriter.ToString());
Response.End();

Resources