To export a gridview to Excel, the reponse content type can be changed to "application/vnd.xls" and then rendered using gridName.RenderControl. Is there any reason this same approach cannot/should not be taken for rendering a listview out to word?
Is there another preferred method for exporting a listview to word?
UPDATE: I have verified that this will work with Word; however, when opening the file, Word displays the html tags (along with the content) from the listview. Below is the code.
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=test.doc");
Response.Charset = "";
Response.ContentType = "application/msword";
var stringWriter = new StringWriter();
var htmlWriter = new HtmlTextWriter(stringWriter);
listView.RenderControl(htmlWriter);
Response.Write(stringWriter.ToString());
Response.End();
The same technique will also work for Microsoft Word. The reason this works the way it does, it that both applications will open and read HTML as the source document format. The filename and the content type are set by the website so that the browser knows the application needed to open the file.
Related
I have a GridView in a WebUserControl in a web page thast uses a master page, and I need to export the grid data to excel and pdf.
I found this code:
Response.AppendHeader("content-disposition", "attachment;filename=ExportedHtml.xls");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.ms-excel";
this.EnableViewState = false;
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
((GridView)Hosts.FindControl("hostsGrid")).RenderControl(hw);
Response.Write(tw.ToString());
Response.End();
But I'm getting this error:
Control 'CPH_Body_Hosts_hostsGrid' of type 'GridView' must be placed inside
a form tag with runat=server.
Even though I have a form runat server on the Master page.
Well I found 2 solutions for this problem:
As King.code commented, it was already solved in GridView must be placed inside a form tag with runat=“server” even after the GridView is within a form tag
I also found this sample code that exports in many other formats Export GridView to doc/access/csv/Excel/pdf/xml/html/text/print
I an trying to open word document on hyperlink click. Now below code is opening dialogbox ans asking for saving.
How to open directly word document without user asking dialogbox for saving or open? just need to popup with word doc.
Response.Clear()
Response.ContentType = "application\msword"
Dim file As New System.IO.FileInfo(Server.MapPath("/UserManual\Carangi Reunderwriting Website User Manual.docx"))
Response.AddHeader("Content-Disposition", "inline; filename=" + file.Name)
Response.AddHeader("Content-Length", file.Length.ToString())
Response.TransmitFile(file.FullName)
Response.Flush()
Response.End()
Browser settings can override the content-disposition header. You might want to check and see if your document opens inline in another browser or on another machine. Seems to me that conservative default settings these days should show a save dialog before opening a word document from a web page.
i want to display *doc,*xls,*pdf in browser window instead of their respected application. i have tried following code, but no luck it prompt me dialog for save/open instead of displaying in browser
//Set the appropriate ContentType.
Response.ContentType = "Application/msword";
//Get the physical path to the file.
string FilePath = MapPath("wordfile.doc");
//Write the file directly to the HTTP content output stream.
Response.AppendHeader("Content-Disposition", "inline;filename=" + "wordfile.doc");
Response.WriteFile(FilePath);
Response.End();
please help
thanks
for any of these proprietary formats you need browser plugins/extensions or ActiveX for IE
Am not sure if its available for office formats.
For PDF setting the content type to "application/pdf" and Content-Disposition to inline should work.
I have an asp.net page in which I have a gridview and a button.
On button click event I have wrote the code which exports the gridview to excel which is working very fine.
But when I try to open that exported excel file it shows a dialog box saying:
"The file you are trying to open is in a different format than
specified by the file extension.Verify that the file is not corrupted
and is from a trusted source before opening the file".
Not only that, i sent that excel file as attachment in gmail and tried to open it in mobile, at that time it opens as an html file.What can I do for this because my client will be using mobile to view mails.
I'd recommend creating an actual Excel file instead of a CSV or HTML using an Excel file name extension.
One easy way to accomplish this is using ClosedXML.
To do this, download the ClosedXML.dll and the DocumentFormat.OpenXml.dll from the codeplex site and add them as references in your ASP.NET project. Then, in your button click event, you can simply set up an Excel workbook, create a worksheet from the same DataTable that you are binding to the GridView, and save the workbook file in the HTTP response. Something like this:
var wb = new ClosedXML.Excel.XLWorkbook();
DataTable dt = GetTheDataTable();
dt.TableName = "This will be the worksheet name";
wb.Worksheets.Add(dt);
Response.Clear();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=\"FileName.xlsx\"");
using (var ms = new System.IO.MemoryStream()) {
wb.SaveAs(ms);
ms.WriteTo(Response.OutputStream);
ms.Close();
}
Response.End();
I'd go with ClosedXML over other alternatives because the license is less restrictive, the documentation is superb, the developer is helpful and friendly, and the project is currently very active.
In your button click event :
protected void btnExcel_Click(object sender, ImageClickEventArgs e)
{
//export to excel
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=FileName.xls");
Response.Charset = "";
// If you want the option to open the Excel file without saving then
// comment out the line below
// Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
//GV is the ID of gridview
GV.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}
and also override this method in your page code behind:
public override void VerifyRenderingInServerForm(Control control)
{
/* Confirms that an HtmlForm control is rendered for the specified ASP.NET
server control at run time. */
}
When I exported to excel, I simply created a comma separated file and gave it an excel file extension. That message went away when I started separating using commas with double quotes.
"one","two","three" rather than one,two,three
I'm having a problem with the conversion to Excel code I'm finding. I am working on a website project in .NET 4.0, and I have created a class for this that does the following (based on
http://mattberseth.com/blog/2007/04/export_gridview_to_excel_1.html):
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("content-disposition",
string.Format("attachment; filename={0}", fileName)); HttpContext.Current.Response.ContentType = "application/ms-excel"; using (StringWriter sw = new StringWriter()) {
using (HtmlTextWriter htw = new HtmlTextWriter(sw)) {
//Create a table to contain the grid
//Add header row
//Add each data row
//Add Footer row
//Render the table into the htmlwriter
// render the htmlwriter into the response
HttpContext.Current.Response.Write(sw.ToString());
HttpContext.Current.Response.End();
}
}
I call this class from a usercontrol that contains a button that is added to a GridView displayed on the page. This works as expected - click the button, you are presented with a download option to either open or save the resulting excel spreadsheet containing the data from the GridView.
However, when I call this from a linkbutton inside a different GridView, I'd like to build a dynamic gridview to contain data and export that. When I do that, I get a ThreadAbortException from the Response.End call in the class.
Question 1: Why do I not get that ThreadAbortException when calling the same code from within a usercontrol? Do usercontrols get their own threads or some other kind of context?
Searching on the error I get when that ThreadAbortException occurs led me to attempt to replace it with ApplicationInstance.CompleteRequest(). When I do that I no longer get the ThreadAbortException, but this breaks the previously working usercontrol - instead of the resulting excel spreadsheet containing the data from the grid, it contains the HTML from the containing page, and at any rate it's easy enough to suppress that error with an empty catch. However, it doesn't fix the direct call with the dynamically generated GridView, that code renders a javascript error: "The message received from the server could not be parsed."
I would love to understand what exactly is going on here, but I'm at the point of needing results regardless of understanding. All the other approaches I've tried (datagrid instead of GridView, etc) run into the same problems, and are essentially the same when it comes down to "taking over"
the current response and using stringwriter and htmlwriter to render the data into a response with excel contentType. And since this demonstrably works in the context of a usercontrol, I am at my wit's end as to why it won't work when called directly...
The problem was actually completely unrelated to the excel export. The “…could not be parsed” error was the key. From these links I got the key, which was that the grid events cause only a partial postback event:
http://forums.asp.net/t/1392827.aspx
http://forums.aspfree.com/net-development-11/gridview-footer-template-button-in-updatepanel-not-posting-back-236087.html
This explains the ThreadAbortException and the “…could not be parsed” error. Adding this to the OnPreRender of the ImageButton was the solution:
protected void addTrigger_PreRender(object sender, EventArgs e)
{
if (sender is ImageButton)
{
ImageButton imgBtn = (ImageButton)sender;
ScriptManager ScriptMgr = (ScriptManager)this.FindControl("ScriptManager1");
ScriptMgr.RegisterPostBackControl(ImgBtn);
}
}
Try instead:
HttpApplication.CompleteRequest()
as per:
http://www.c6software.com/codesolutions/dotnet/threadabortexception.aspx
They discuss the additional html being flished
use this
Response.Clear()
Response.AddHeader("content-disposition", atchment;filename=fm_specification.xls")
Response.Charset = ""
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.ContentType = "application/vnd.xls"
Dim stringWrite As System.IO.StringWriter = New System.IO.StringWriter
Dim htmlwrite As System.Web.UI.HtmlTextWriter = New HtmlTextWriter(stringWrite)
GridView1.RenderControl(htmlwrite)
Response.Write(stringWrite.ToString)
Response.End()
instead of gridview1 you can use div
dont forget to add this on your page
Public Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)
End Sub
The event on which the Export to excel code is called, must make a full postback. the issue is because it does only a partial postback.
I had the same error and it got solved when i did a full postback.
Hope this helps someone.