ASP Export to Excel Client side and have browser knwo what application it is - asp.net

I'm using the below code and I'm specifying what type of application it is. However, when prompted to open the application the browser does not know what type of file it is. How can I make the browser already want to open it as an excel?
Any help is appreciated
public static void ExportToSpreadsheet(DataTable table, string name)
{
HttpContext context = HttpContext.Current;
context.Response.Clear();
foreach (DataColumn column in table.Columns)
{
context.Response.Write(column.ColumnName + "\t");
}
context.Response.Write(Environment.NewLine);
foreach (DataRow row in table.Rows)
{
for (int i = 0; i < table.Columns.Count; i++)
{
context.Response.Write(row[i].ToString() + "\t");
}
context.Response.Write(Environment.NewLine);
}
context.Response.ContentType = "application/ms-excel";
context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + name+ ".xls");
context.Response.End();
}

try:
Response.ContentType = "application/vnd.ms-excel";
or for xlsx
Response.ContentType = "application/application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

Related

Export to CSV Website asp

I have a GridView and when I click Export Button to export my data into CSV. I click the button and it takes all the data correctly but it doesn't show anything, no popup to ask me to open or to save .
Here is my code
protected void btnExport_Click(object sender, EventArgs e)
{
ExportCSV();
}
protected void ExportCSV()
{
GridViewSW.DataSource = ViewState["source"];
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=Orders.csv");
Response.Charset = "";
Response.ContentType = "application/text";
GridViewSW.AllowPaging = false;
GridViewSW.DataBind();
StringBuilder columnbind = new StringBuilder();
for (int k = 0; k < GridViewSW.Columns.Count; k++)
{
columnbind.Append(GridViewSW.Columns[k].HeaderText + ",");
}
columnbind.Append("\r\n");
for (int i = 0; i < GridViewSW.Rows.Count; i++)
{
for (int j = 0; j < GridViewSW.Columns.Count; j++)
{
columnbind.Append(GridViewSW.Rows[i].Cells[j].Text + ",");
}
columnbind.Append("\r\n");
}
Response.Output.Write(columnbind.ToString());
Response.Flush();
Response.End();
}
NEW EDIT
I changed the code a little bit. Now i have the csv file and he has all the data in, but when I click the button it doesn't show any dialog box with open or save.
string fullSavePath = HttpContext.Current.Server.MapPath(string.Format("~/csv/Orders.csv"));
StreamWriter sr = new StreamWriter(fullSavePath);
DataSet ds = (DataSet)ViewState["source"];
MyDateTime date = new MyDateTime();
DataTableReader dr = ds.Tables[0].CreateDataReader();
while (dr.Read())
{
sr.Write(dr.GetValue(0) + "," + date.ConvertToDate(Convert.ToInt64(dr.GetValue(2))) + "," + date.ConvertToDate(Convert.ToInt64(dr.GetValue(3))) + "," + dr.GetValue(4) + "\r\n");
}
sr.Flush();
sr.Close();
sr.Dispose();
System.IO.FileInfo file = new System.IO.FileInfo(fullSavePath);
System.Web.HttpContext context = System.Web.HttpContext.Current;
System.Web.HttpResponse response = context.Response;
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "text/csv";
Response.AddHeader("Content-Disposition", string.Format("attachment; filename =" + "Orders.csv"));
// Response.TransmitFile(fullSavePath);
Response.WriteFile(file.FullName);
// Response.Flush();
context.ApplicationInstance.CompleteRequest();
// Response.End();
// Response.Close();
I believe you need to change your content type to "text/csv"
Response.ContentType = "text/csv";

Prevent download when exporting Gridview to Excel

I am trying to export data in a Gridview to Excel and store that file in a folder on server.
I have done this part. The only thing I want to do is,
I want to prevent downloading the Excel file.
Please find my code below.
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "order.xls"));
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gridX.AllowPaging = false;
bindX();
gridX.HeaderRow.Style.Add("background-color", "#FFFFFF");
for (int i = 0; i < gridX.HeaderRow.Cells.Count; i++)
{
gridX.HeaderRow.Cells[i].Style.Add("background-color", "#df5015");
}
gridX.RenderControl(htw);
//Response.Write(sw.ToString());
string renderedGridView = sw.ToString();
string path = Server.MapPath("~/Order/od/x");
System.IO.File.WriteAllText(path + "/order" + lblF.Text + ".xls", renderedGridView);
sw.Close();
htw.Close();
Thanks in advance.
Use this code by editing as per your need :
private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e)
{
e.Cancel = true;
WebClient client = new WebClient();
client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(client_DownloadDataCompleted);
client.DownloadDataAsync(e.Url);
}
void client_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
{
string filepath = textBox1.Text;
File.WriteAllBytes(filepath, e.Result);
MessageBox.Show("File downloaded");
}
Hope this will help you.
I got the answer.
Code
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gridX.AllowPaging = false;
bindX();
gridX.HeaderRow.Style.Add("background-color", "#FFFFFF");
for (int i = 0; i < gridX.HeaderRow.Cells.Count; i++)
{
gridX.HeaderRow.Cells[i].Style.Add("background-color", "#df5015");
}
gridX.RenderControl(htw);
//Response.Write(sw.ToString());
string renderedGridView = sw.ToString();
string path = Server.MapPath("~/Order/od/x");
System.IO.File.WriteAllText(path + "/order" + lblF.Text + ".xls", renderedGridView);
sw.Close();
htw.Close();

How to download excel file to a specific folder in asp.net

I need to download the excel to the specific folder
Example : D:\email
Now i was able to download the excel file in downloads ....but i need to download in D:\email
this is my code to create excel file :
protected void UploadDataTableToExcel(DataTable dtRecords)
{
string XlsPath = Server.MapPath(#"~/Add_data/test.xls");
string attachment = string.Empty;
if (XlsPath.IndexOf("\\") != -1)
{
string[] strFileName = XlsPath.Split(new char[] { '\\' });
attachment = "attachment; filename=" + strFileName[strFileName.Length - 1];
}
else
attachment = "attachment; filename=" + XlsPath;
try
{
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/vnd.ms-excel";
string tab = string.Empty;
foreach (DataColumn datacol in dtRecords.Columns)
{
Response.Write(tab + datacol.ColumnName);
tab = "\t";
}
Response.Write("\n");
foreach (DataRow dr in dtRecords.Rows)
{
tab = "";
for (int j = 0; j < dtRecords.Columns.Count; j++)
{
Response.Write(tab + Convert.ToString(dr[j]));
tab = "\t";
}
Response.Write("\n");
}
Response.End();
}
catch (Exception ex)
{
//Response.Write(ex.Message);
}
}
you can manually move the file after download using
string sourceFile = #"C:\Users\test\Documents\Downloads\test.xls";
string destinationFile = #"D:\emails\test.xls";
// To move a file or folder to a new location:
System.IO.File.Move(sourceFile, destinationFile);

Export data table to Excel sheet

I want to export data from data table to Excel file. I need to save the file on server. I am using the console application for this project.
Since you haven't mentioned if excel is installed, i recommend EPPlus to create the excel file. It has a convenient method LoadFromDataTable:
using (var pck = new ExcelPackage())
{
var ws = pck.Workbook.Worksheets.Add("Worksheet-Name");
ws.Cells["A1"].LoadFromDataTable(dataTable1, true, OfficeOpenXml.Table.TableStyles.Medium1);
using(var fileStream = File.Create(path))
pck.SaveAs(fileStream);
}
Edit i've only just seen that you have tagged export-to-csv.
var lines = dataTable1.AsEnumerable()
.Select(r => string.Join(",", r.ItemArray));
string csv = string.Join(Environment.NewLine, lines);
File.AppendAllText(path, csv);
if (DtReqDetails != null)
{
string attachment = "attachment; filename=History.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/vnd.ms-excel";
string tab = "";
foreach (DataColumn dc in DtReqDetails.Columns)
{
Response.Write(tab + dc.ColumnName);
tab = "\t";
}
Response.Write("\n");
int i;
foreach (DataRow dr in DtReqDetails.Rows)
{
tab = "";
for (i = 0; i < DtReqDetails.Columns.Count; i++)
{
Response.Write(tab + dr[i].ToString());
tab = "\t";
}
Response.Write("\n");
}
Response.End();
}
If you are using MS SQL, then they have a built-in procedure for exporting a table to an Excel spreadsheet. No coding required.

Streaming a zip file over http in .net with SharpZipLib

I'm making a simple download service so a user can download all his images from out site.
To do that i just zip everything to the http stream.
However it seems everything is stored in memory, and the data isn't sent til zip file is complete and the output closed.
I want the service to start sending at once, and not use too much memory.
public void ProcessRequest(HttpContext context)
{
List<string> fileNames = GetFileNames();
context.Response.ContentType = "application/x-zip-compressed";
context.Response.AppendHeader("content-disposition", "attachment; filename=files.zip");
context.Response.ContentEncoding = Encoding.Default;
context.Response.Charset = "";
byte[] buffer = new byte[1024 * 8];
using (ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipOutput = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(context.Response.OutputStream))
{
foreach (string fileName in fileNames)
{
ICSharpCode.SharpZipLib.Zip.ZipEntry zipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(fileName);
zipOutput.PutNextEntry(zipEntry);
using (var fread = System.IO.File.OpenRead(fileName))
{
ICSharpCode.SharpZipLib.Core.StreamUtils.Copy(fread, zipOutput, buffer);
}
}
zipOutput.Finish();
}
context.Response.Flush();
context.Response.End();
}
I can see the the worker process memory growing while it makes the file, and then releases the memory when its done sending. How do i do this without using too much memory?
Disable response buffering with context.Response.BufferOutput = false; and remove the Flush call from the end of your code.
use Response.BufferOutput = false; at start of ProcessRequest and flush response after each file.
FYI. This is working code to recursively add an entire tree of files, with streaming to browser:
string path = #"c:\files";
Response.Clear();
Response.ContentType = "application/zip";
Response.AddHeader("Content-Disposition", string.Format("attachment; filename=\"{0}\"", "hive.zip"));
Response.BufferOutput = false;
byte[] buffer = new byte[1024 * 1024];
using (ZipOutputStream zo = new ZipOutputStream(Response.OutputStream, 1024 * 1024)) {
zo.SetLevel(0);
DirectoryInfo di = new DirectoryInfo(path);
foreach (string file in Directory.GetFiles(di.FullName, "*.*", SearchOption.AllDirectories)) {
string folder = Path.GetDirectoryName(file);
if (folder.Length > di.FullName.Length) {
folder = folder.Substring(di.FullName.Length).Trim('\\') + #"\";
} else {
folder = string.Empty;
}
zo.PutNextEntry(new ZipEntry(folder + Path.GetFileName(file)));
using (FileStream fs = File.OpenRead(file)) {
ICSharpCode.SharpZipLib.Core.StreamUtils.Copy(fs, zo, buffer);
}
zo.Flush();
Response.Flush();
}
zo.Finish();
}
Response.Flush();

Resources