I am trying to export the Gridview data to docx, but it doesnot work.
public static void SendToUserWord(GridView grid, string fileName, string type)
{
var response = HttpContext.Current.Response;
response.Clear();
response.AddHeader("content-disposition", string.Format("attachment; filename=\"{0}\"", fileName));
response.Charset = "";
response.ContentType = type == "doc" ? "application/vnd.ms-word" : "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
response.ContentEncoding = Encoding.Default;
response.Write("<head><meta http-equiv=\"content-type\" content=\"text/html; charset="
+ Encoding.Default.WebName + "\"></head>");
response.Write(#"<style> td { mso-number-format:\#; } </style>");
using (var writer = new HtmlTextWriter(response.Output))
{
grid.RenderControl(writer);
}
response.End();
}
How do export to doxc?
Related
I have the following method, which converts HTML to Word Document and sends it as a download to user.
public static void HtmlToWordDownload(string HTML, string FileName, string title = "", bool border = false)
{
lock (LockMulti)
{
string strBody = string.Empty;
strBody = #"<html xmlns:o='urn:schemas-microsoft-com:office:office' " +
"xmlns:w='urn:schemas-microsoft-com:office:word'" +
"xmlns='http://www.w3.org/TR/REC-html40'>" +
"<head><title>:" + title + "</title>" +
"<!--[if gte mso 9]><xml><w:WordDocument><w:View>Print</w:View><w:Zoom>100</w:Zoom>" +
"<w:DoNotOptimizeForBrowser/></w:WordDocument></xml><![endif]-->" +
"<style> #page Section1 {size:8.27in 11.69in; mso-first-footer:ff1; mso-footer: f1; mso-header: h1; " +
((border == true) ? "border:solid navy 2.25pt; padding:24.0pt 24.0pt 24.0pt 24.0pt; " : "") +
"margin:0.6in 0.6in 0.6in 0.6in ; mso-header-margin:.1in; " +
"mso-footer-margin:.1in; mso-paper-source:0;} " +
"div.Section1 {page:Section1;} p.MsoFooter, li.MsoFooter, " +
"div.MsoFooter{margin:0in; margin-bottom:.0001pt; " +
"mso-pagination:widow-orphan; tab-stops:center 3.0in right 6.0in; " +
"font-size:12.0pt; font-family:'Arial';} " +
"p.MsoHeader, li.MsoHeader, div.MsoHeader {margin:0in; " +
"margin-bottom:.0001pt; mso-pagination:widow-orphan; tab-stops:center " +
"3.0in right 6.0in; font-size:12.0pt; font-family:'Arial';}--></style></head> ";
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Charset = "";
HttpContext.Current.Response.ContentType = "application/vnd.ms-word";
HttpContext.Current.Response.AddHeader("Content-Disposition", "inline;filename=" + FileName + ".doc");
StringBuilder htmlCode = new StringBuilder();
htmlCode.Append(strBody);
htmlCode.Append("<body><div class=Section1>");
htmlCode.Append(HTML);
htmlCode.Append("</div></body></html>");
HttpContext.Current.Response.Write(htmlCode.ToString());
HttpContext.Current.Response.End();
HttpContext.Current.Response.Flush();
}
}
Now I don't want to give it as a download to user directly, I want to first save it on a local folder of my server and then give it as download. How do I do that?
You might try to serve the file you generate like this at the point that you do htmlCode.ToString():
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(file.FullName);
Response.End();
Another method is save file and read it as a byte array and serve it like this:
byte[] Content= File.ReadAllBytes(FilePath); //missing ;
Response.ContentType = "text/csv";
Response.AddHeader("content-disposition", "attachment; filename=" + fileName + ".csv");
Response.BufferOutput = true;
Response.OutputStream.Write(Content, 0, Content.Length);
Response.End();
or
string filename="Connectivity.doc";
if (filename != "")
{
string path = Server.MapPath(filename);
System.IO.FileInfo file = new System.IO.FileInfo(path);
if (file.Exists)
{
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(file.FullName);
Response.End();
}
else
{
Response.Write("This file does not exist.");
}
}
Otherwise
Once you saved the word/pdf file on the server on some temp path you can use an HTTP Handler (.ashx) to download a file, like this:
ExamplePage.ashx:
public class DownloadFile : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "text/plain";
response.AddHeader("Content-Disposition",
"attachment; filename=" + fileName + ";");
response.TransmitFile(Server.MapPath("FileDownload.csv"));
response.Flush();
response.End();
}
public bool IsReusable
{
get
{
return false;
}
}
}
Then you can call the HTTP Handler from the button click event handler, like this:
Markup:
<asp:Button ID="btnDownload" runat="server" Text="Download File"
OnClick="btnDownload_Click"/>
Code-Behind:
protected void btnDownload_Click(object sender, EventArgs e)
{
Response.Redirect("PathToHttpHandler/DownloadFile.ashx");
}
Passing a parameter to the HTTP Handler:
You can simply append a query string variable to the Response.Redirect(), like this:
Response.Redirect("PathToHttpHandler/DownloadFile.ashx?yourVariable=yourValue");
Then in the actual handler code you can use the Request object in the HttpContext to grab the query string variable value, like this:
System.Web.HttpRequest request = System.Web.HttpContext.Current.Request;
string yourVariableValue = request.QueryString["yourVariable"];
// Use the yourVariableValue here
Note - it is common to pass a filename as a query string parameter to suggest to the user what the file actually is, in which case they can override that name value with Save As...
In my method in controller I use the following code to save pdf.
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(htmlContent);
HtmlNode node = doc.GetElementbyId("DetailsToPDF");
HtmlToPdfConverter htmlToPdf = new HtmlToPdfConverter();
var pdfBytes = htmlToPdf.GeneratePdf("<html><body>" + node.InnerHtml + "</body></html>");
Response.ContentType = "application/pdf";
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.AddHeader("Content-Disposition", "attachment; filename=TEST.pdf");
Response.BinaryWrite(pdfBytes);
Response.Flush();
Response.End();
Everything has passed without any exceptions in debugger. However file is not saved. What am I doing wrong?
The recommended way to return a File in ASP.NET MVC is using the File() helper method:
public ActionResult Download()
{
// Starting with pdfBytes here...
// ...
var pdfBytes = htmlToPdf.GeneratePdf("<html><body>" + node.InnerHtml + "</body></html>");
var contentDisposition = new System.Net.Mime.ContentDisposition
{
FileName = "TEST.pdf",
Inline = false
};
Response.AppendHeader("Content-Disposition", contentDisposition.ToString());
return File(pdfBytes, "application/pdf");
}
string path = Server.MapPath("~/Content/files/newPDFFile.pdf");
WebClient client = new WebClient();
Byte[] buffer = client.DownloadData(path);
if (buffer != null)
{
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=" + "PDFfile.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite(buffer);
Response.End();
}
I have the following code to download a DataTable as an excel file.This code is working if i download as ".xls" format , but its not working if i download as ".xlsx" format.
var filename = "Students.xlsx";
var sw = new System.IO.StringWriter();
var hw = new System.Web.UI.HtmlTextWriter(sw);
var grid = new System.Web.UI.WebControls.DataGrid();
grid.DataSource = dt;
grid.DataBind();
//customizing format
grid.HeaderStyle.BackColor = System.Drawing.Color.LightGray;
grid.HeaderStyle.Font.Bold = true;
grid.RenderControl(hw);
//string style = #"<style> .textmode { mso-number-format:\#; } </style>";
Response.Clear();
Response.Buffer = true;
//Response.ContentType = "application/vnd.ms-excel";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");
Response.Write(sw.ToString());
Response.Flush();
Response.End();
If i download as ".xlsx" format its giving following error and unable to open excel file.How can i download the excel with ".xlsx" format ?
string filePath1 = (sender as LinkButton).CommandArgument;
string filepath = ("D:\\RetailAgreement\\" + filePath1);
FileInfo myfile = new FileInfo(filepath);
if (filePath1 != "")
{
Response.ClearContent();
Response.AddHeader("Content-Disposition", "attachment; filename=" + myfile.Name);
Response.AddHeader("Content-Length", myfile.Length.ToString());
Response.ContentType = ReturnExtension(myfile.Extension.ToLower());
Response.TransmitFile(myfile.FullName);
Response.End();
}
I tried like this but it is not working ,
I don't know where i went wrong. I am using C#3.0
File.Copy("D:\\RetailAgreement\\",Server.Mapth("YourAplicationPath\\MyFiles"), true);
//Copy Files to Your Application Path
string path = Server.MapPath("~\MyFiles" + filePath1");
System.IO.FileInfo file = new System.IO.FileInfo(path);
string Outgoingfile = "myfile.xlsx";
if (file.Exists)
{
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("Content-Disposition", "attachment; filename=" + Outgoingfile);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.WriteFile(file.FullName);
Response.Flush();
Response.Close();
}
else
{
Response.Write("This file does not exist.");
}
use this code.
string path = Server.MapPath("~/DownloadedExcelFilesOp4/myfile.xlsx");
System.IO.FileInfo file = new System.IO.FileInfo(path);
string Outgoingfile = "myfile.xlsx";
if (file.Exists)
{
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("Content-Disposition", "attachment; filename=" + Outgoingfile);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.WriteFile(file.FullName);
Response.Flush();
Response.Close();
}
else
{
Response.Write("This file does not exist.");
}
I had problem with export data to .csv file. I use 2 methods.
Encoding csvEncoding = new UTF8SignatureEncoding();
byte[] csvFile = TestByte(CsvContentDelimiter.NewLine, CsvContentDelimiter.Semicolon, csvEncoding);
string attachment = String.Format("attachment; filename={0}.csv", "docs_inv");
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.ContentType = "text/csv";
Response.ContentEncoding = csvEncoding;
Response.AppendHeader("Content-Disposition", attachment);
Response.BinaryWrite(csvFile);
Response.Flush();
Response.End();
And
public byte[] TestByte(CsvContentDelimiter rowDelimiter, CsvContentDelimiter columnDelimiter, Encoding encoding)
{
StringBuilder sb = new StringBuilder();
sb.Append("product;");
return encoding.GetBytes(sb.ToString());
}
This code create .csv file, but file have bad Encoding and i see only some "hash"
Here is a fully working example using UTF8 formatting. It uses your own code so shows that it is your Encoding that is causing the issue:
namespace WebApplication1
{
using System;
using System.Text;
public partial class _Default : System.Web.UI.Page
{
protected void btnExport_Click(object sender, EventArgs e)
{
// Use UTF8 encoding
Encoding csvEncoding = Encoding.UTF8;
byte[] csvFile = TestByte(csvEncoding);
string attachment = String.Format("attachment; filename={0}.csv", "docs_inv");
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.ContentType = "text/csv";
Response.ContentEncoding = csvEncoding;
Response.AppendHeader("Content-Disposition", attachment);
Response.BinaryWrite(csvFile);
Response.Flush();
Response.End();
}
public byte[] TestByte(Encoding encoding)
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat("Record1,Fred,Bloggs,26{0}", Environment.NewLine);
sb.AppendFormat("Record2,John,Smith,32{0}", Environment.NewLine);
return encoding.GetBytes(sb.ToString());
}
}
}