How to save created excel file to Client pc in ASP.NET

前端 未结 4 668
南旧
南旧 2021-01-25 06:26

I am creating a excel report and html report in asp.net when I clik the button and my application create it and save to the client desktop but, it is not working correctly becau

4条回答
  •  独厮守ぢ
    2021-01-25 06:44

    You can write excel file to response HttpResponse.WriteFile Method

    string CurrentDate;
    DateTime saveNow = DateTime.Now;
    CurrentDate = saveNow.Date.ToShortDateString();
    string reportContent = prepareHTM();
    
    string pathFile = Environment.GetFolderPath(Environment.SpecialFolder.CommonDesktopDirectory) + "\\As_Build_Report_ "+ CurrentDate + ".html";
    
    using (StreamWriter outfile = new StreamWriter(pathFile, true))
    {
        outfile.WriteLine(reportContent);
    }
    
    System.IO.FileInfo file = new System.IO.FileInfo(pathFile); 
    Response.Clear(); 
    Response.Charset="UTF-8"; 
    Response.ContentEncoding=System.Text.Encoding.UTF8; 
    Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name); 
    Response.AddHeader("Content-Length", file.Length.ToString());    
    Response.ContentType = "application/ms-excel";  
    Response.WriteFile(file.FullName); 
    Response.End(); 
    

提交回复
热议问题