Click here to Skip to main content
15,879,095 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Below is my code to download the data in excel but the problem is while downloading it is not showing that the file is getting downloaded moreover i am giving the path in this way as given below to download the file in downloads folder but i should not use this because it works in local host but it will not work when hosted in server.how can i download into downloads folder with showing the downloading file at bottom


string pathUser = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
           string pathDownload = Path.Combine(pathUser, "Downloads\\");

protected void btnExportExcel_Click(object sender, EventArgs e)
    {
string pathUser = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
               string pathDownload = Path.Combine(pathUser, "Downloads\\");
 DataTable dtExcel = (DataTable)ViewState["data"];
ExportToExcel(dsExcel, pathDownload + "\\" + file.xls");
}
 private void ExportToExcel(DataSet table, string filePath)
    {

        int tablecount = table.Tables.Count;
        StreamWriter sw = new StreamWriter(filePath, false);
        sw.Write(@"<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.0 Transitional//EN"">");
        sw.Write("<font style='font-size:10.0pt; font-family:Calibri;'>");

        for (int k = 0; k < tablecount; k++)
        {


            sw.Write("<BR><BR><BR>");
            sw.Write("<Table border='1' bgColor='#ffffff' borderColor='#000000' cellSpacing='0' cellPadding='0' style='font-size:10.0pt; font-family:Calibri; background:'#1E90FF'> <TR>");


            int columnscount = table.Tables[k].Columns.Count;

            for (int j = 0; j < columnscount; j++)
            {
                sw.Write("<Td bgColor='#87CEFA'>");
                sw.Write("");
                //sw.Write(table.Columns[j].ToString());
                sw.Write(table.Tables[k].Columns[j].ToString());

                sw.Write("");
                sw.Write("</Td>");
            }
            sw.Write("</TR>");
            foreach (DataRow row in table.Tables[k].Rows)
            {
                sw.Write("<TR>");
                for (int i = 0; i < table.Tables[k].Columns.Count; i++)
                {
                    sw.Write("<Td>");
                    sw.Write(row[i].ToString());
                    sw.Write("</Td>");
                }
                sw.Write("</TR>");
            }
  sw.Write("</Table>");
            //sw.Write("<BR><BR><BR><BR>");
            //sw.Write("\n");
            //sw.Write(string.Format("Line1{0}Line2{0}", Environment.NewLine));


            sw.Write("</font>");

        }
        sw.Close();
    }


the below two lines that i am using in btnexportexcel should not be used


string pathUser = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
               string pathDownload = Path.Combine(pathUser, "Downloads\\");


What I have tried:

he problem is while downloading it is not showing that the file is getting downloaded moreover i am giving the path in this way as given below to download the file in downloads folder but i should not use this because it works in local host but it will not work when hosted in server
Posted
Updated 15-Jun-17 22:37pm
Comments
Maciej Los 16-Jun-17 4:27am    
Cross-post: https://stackoverflow.com/questions/44584182/how-can-i-save-excel-file-in-downloads-folder-using-asp-net-c-sharp

You're not downloading the file to the client, you're simply writing it to the filesystem of the machine the code is running on. When that was your local machine it looked like it was working, but now the code is deployed to a server it is writing the file to the server.

You can't save files to the client system from your server code, imagine the security implications if web sites could do that? You'll need to transmit the file to the client instead so that they'll get the "download or open" box, and you can't specify where on the machine the file is saved or if it is saved at all.

Google "asp.net download file to client" for examples of how to do this.
 
Share this answer
 
Comments
kav@94 16-Jun-17 4:30am    
i had tried but they are not working while downloading i am getting exception
F-ES Sitecore 16-Jun-17 4:33am    
Then the code you are using is wrong, update the original question with the code you are trying, what the exception is, and what line it appears on.
kav@94 16-Jun-17 4:36am    
Response.ContentType = "APPLICATION/OCTET-STREAM";
String Header = "Attachment; Filename=XMLFile.xml";
Response.AppendHeader("Content-Disposition", Header);
System.IO.FileInfo Dfile = new System.IO.FileInfo(Server.MapPath("here i had gien my application folder name"));
Response.WriteFile(Dfile.FullName);
//Don't forget to add the following line
Response.End();

this is the code that i had used but it is giving exception because i am using stream writer in my code and this code is not working i should be able to downlad into downloads folder on button click
F-ES Sitecore 16-Jun-17 4:42am    
What is the exception and on what line?
You cannot do that: download files in production are on a separate computer to which your server code has no access. You cannot use a StreamWriter to write a file directly to the user at all, and you cannot control what happens to it once the download has started as that is totally up to the user and his browser settings. You cannot specify a folder for the file to be saved in at all, or even specify that the file should be saved instead of opened.

Instead you either give teh user a link to click:
HTML
<a href="serverFilePath.xlsx" >Click to Save Excel document</a>

Or you send it via the Response object:
C#
byte[] fileContent = File.ReadAllBytes(path);
    HttpContext.Current.Response.Clear();
    HttpContext.Current.Response.AddHeader("Content-Disposition attachment; filename=myFile.xlsx");
    HttpContext.Current.Response.AddHeader("Content-Length", fileContent.Length.ToString());
    HttpContext.Current.Response.ContentType = "application/octet-stream";
    HttpContext.Current.Response.BinaryWrite(fileContent);
    HttpContext.Current.Response.End();
 
Share this answer
 
Comments
OriginalGriff 16-Jun-17 5:38am    
To quote myself: "you cannot control what happens to it once the download has started as that is totally up to the user and his browser settings"
You cannot control the folder it ends up in, or even that it ends up being saved at all.
kav@94 16-Jun-17 5:41am    
byte[] fileContent = File.ReadAllBytes(path);
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("Content-Disposition attachment; filename=myFile.xlsx");
HttpContext.Current.Response.AddHeader("Content-Length", fileContent.Length.ToString());
HttpContext.Current.Response.ContentType = "application/octet-stream";
HttpContext.Current.Response.BinaryWrite(fileContent);
HttpContext.Current.Response.End();

by placing this code i am getting error near path and near add header
OriginalGriff 16-Jun-17 5:50am    
Have you ever considered reading example code with the view that the author can't see exactly what you need to type and might have to use placeholders.
You know, such as 'path' where you need to put the actual path to the file you need to access for example? And "MyFile" where he doesn't know the name of the file you want to save it as? :sigh:
kav@94 16-Jun-17 5:59am    
i know that i should provide the path for the excel to get download but i cannot pass this path because when hosted in server it is giving error so i got strucked

string pathUser = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
string pathDownload = Path.Combine(pathUser, "Downloads\\");
OriginalGriff 16-Jun-17 6:22am    
The user profile is useless in a web site, which user do you think you are? IIS does not use a user id that is of any use to you, and does not have a "regular" folder under "Users".

The folder you need will be a part of your website structure, almost certainly, and that means you probably need something like Server.MapPath(@"~\Downloads\TheFileIWantToAccess");

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900