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

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

Related

C# Response.ContentType Creating multiple tabs in Excel

I'm generating an Excel report in C# and need to add a second tab to the Excel file that will contain reference data. How do I achieve this without using ClosedXML ?
Response.AddHeader("content-disposition", "attachment; filename=" + fname);
Response.ContentType = "application/vnd.ms-excel";
var writer = new System.IO.StringWriter();
var htmlTextWriter = new HtmlTextWriter(writer);
dataGrid.RenderControl(htmlTextWriter);
Response.Write(writer.ToString());
Response.End();

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();

How do I save a word document to my file system instead of printing it out?

In my application I print my div to a word document like this:
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=testme.doc");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/doc";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
divExport.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
Instead of opening it on the browser How would I go about saving it to a path? Generally when using ItextSharp I would declare the path and the existing template file.
private static string AppRelativePath_1page = "~/DesktopModules/MyFolder";
private static string AppAbsolutePath_1page = HttpContext.Current.Server.MapPath(AppRelativePath_1page);
In this case there is no existing template file. How would I go about creating this file in my server folder?
Open a StreamWriter, and instead of writing to the Response object, write to your StreamWriter.
you do it by using Streamwriter
using (StreamWriter sw = new StreamWriter(Path))
{
sw.Write(stringWrite.ToString());
}

Creating multiple sheets of excel from c# using streamwriter

I'm using the streamwriter to create an excel file. but the problem is that I didn't find a way to create multiple sheets and specify their names from c#. Also I wanted to draw a chart on excel using streamwriter. So does anybody have an idea how to do both things using streamwriter and not excel instance??
My code is like this:
String sPath = Environment.GetEnvironmentVariable("TEMP") + "\\Synthese.xls";
FileStream oFile = new FileStream(sPath, FileMode.Create);
StreamWriter oWriter = new StreamWriter(oFile, System.Text.Encoding.UTF8);
oWriter.WriteLine("<table border='1' border-color='#ffffff' style=font-weight:bold;><tr>");
...
oWriter.Close();
oFile.Close();
FileInfo myFile = new FileInfo(sPath);
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + myFile.Name);
Response.AddHeader("Content-Length", myFile.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(myFile.FullName);
Response.Flush();
Response.End();
Any help is highly appreciated.
It looks like you're trying to write pseudo-HTML to a xls file and hope it works... I'd be surprised if Excel even opens it.
You are better off using a proper tool for the job.
I suggest looking at EPPlus which allows you to create excel documents in C# with all the features you are describing.
Example lifted from the codeplex site:
FileInfo newFile = new FileInfo(outputDir.FullName + #"\sample6.xlsx");
ExcelPackage pck = new ExcelPackage(newFile);
//Add the Content sheet
var ws = pck.Workbook.Worksheets.Add("Content");
ws.View.ShowGridLines = false;
//Headers
ws.Cells["B1"].Value = "Name";
ws.Cells["C1"].Value = "Size";
ws.Cells["D1"].Value = "Created";
ws.Cells["E1"].Value = "Last modified";
ws.Cells["B1:E1"].Style.Font.Bold = true;
Additionally it is advisable to use using statements when using IDisposable classes such as FileStream:
using (var stream = new FileStream(path, FileMode.Create))
{
// ... stuff using stream in here
}

DataGrid to excel not showing automatic gridlines

Wondering if anyone can assist. I have an .ashx file which creates an excel document which is populated with a C# DataGrid. This all works well the only problem is when I open the excel document the automatic gridlines are turned off. Is there a way to enable them?
Thanks in advance,
Air
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.Charset = "";
response.ContentEncoding = System.Text.Encoding.Default;
response.ContentType = "application/vnd.ms-excel";
response.AddHeader("Content-Disposition", "attachment;filename=\"dataImportTemplate.xls\"");
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
System.Web.UI.WebControls.DataGrid dg = new System.Web.UI.WebControls.DataGrid();
dg.DataSource = ds.Tables[0];
dg.ShowHeader = false;
dg.DataBind();
dg.RenderControl(htw);
response.Write(sw.ToString());
}
}
If you export to a csv it keeps the gridlines.
This is a pretty simple workaround that a lot of people opt to use.
See similear post Here
That post includes a helper function that supposedly can add the gridlines to your export.
Hope this helps.

Categories