So I am using this code, to export a formview to Word.
Its works great..But I want it to export to PDF so that it cannot be edited. Or may be to a word doc so that not body can make changes.
protected void Button1_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition",
"attachment;filename=Report.doc");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-word";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
FormView1.DataBind();
FormView1.RenderControl(hw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
The problem is, even when I change the content type and header element in the above code, it says that the output pdf has errors.
I really want to either convert the doc to pdf or generate pdf using this code.
Please help.
Thanks..
Your best bet to create PDFs in ASP.NET is to use a plug in like iTextSharp. I have used it in the past and it's very simple and free.
http://itextpdf.com/
As mentioned above, creating PDF using one of the existing libraries would be more efficient.
But if you're down to use interop, you can download save as pdf plugin for Microsoft Office.
And then pass "pdf" format to SaveAs method
Alternatively, you can apply several properties to your word document:
1. Mark as Final doc.Final = true;
2. Restrict editing
For newer version of Word, there's a Protect method, that provides a convenient way of restricting editing: http://msdn.microsoft.com/en-us/library/ms178793.aspx
Related
Here's the export piece of my code:
private void ExportGridView()
{
// Exports the data in the GridView to Excel
// First, fill the datagrid with the results of the session variable
DataTable gridDataSource = (DataTable)Session["SSRegisterSplit"];
DataGrid dgGrid = new DataGrid();
dgGrid.DataSource = gridDataSource;
dgGrid.DataBind();
// Exports the data in the GridView to Excel
string attachment = "attachment; filename=Claim_Details_" + LPI_ID + ".xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
dgGrid.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
When it exports, it shows up in my footer automatically with an option to Open or Save.
If I choose "Open", Excel launches and then I get an error box:
The file you are trying to open, 'Claim_Details_1586.xls' 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. Do you want to open the file now?
If I choose 'Yes', it opens the file but not all the records are in it.
Any ideas on what's happening/how to fix it?
EDIT:
Putting a break point in the function, I noticed that when it gets to Response.End(); it throws the error:
Thread Was being Aborted.
I think this is what you want:
Is Response.End() considered harmful?
Don't use Response.End()
Consider using:
Response.Flush()
Response.SuppressContent = True
HttpContext.Current.ApplicationInstance.CompleteRequest()
—————————————————————————————
However. I'm pretty sure that the ”save an html file with .XLS extension” will always result in Excel showing an error.
The alternative is to pick something from http://nugetmusthaves.com/Tag/Excel to create a proper xls file. I've used EPPlus before but this page suggests that ClosedXML will do it for you in 5 lines.
If you aren't familiar with installing NuGet packages, then start here: https://learn.microsoft.com/en-gb/nuget/tools/package-manager-ui
I have a C#/asp.net program that stores data in a datagrid and then uses HttpResponse to create an Excel file from it. This worked well until Microsoft made security changes. Here's some information on that change: http://www.networksteve.com/exchange/topic.php/XLS_file_will_not_open_in_Excel_2016,_only_gray_view/?TopicId=77375&Posts=3. The solutions such as turning off Excel security and uninstalling the patch the caused the problem are not acceptable for my client. The official Microsoft answer is "The best option is to move away from using HTML wrapped as .XLS. If you use native formats (e.g. XLS, XLSX, XLSB) which will open in protected view when untrusted, this will provide some level of protection from the documents being opened." http://answers.microsoft.com/en-us/office/forum/office_2010-excel/windows-installed-updates-and-now-downloaded-excel/069b0fdf-d085-4322-b298-5976d0efa9ce?rtAction=1468539460673
My question is, how do I do that? I tried using the Microsoft.Interop and found multiple people saying this is not a good solution. I could never get that working anyway; see that discussion here: How can I download an Excel file to the user's download folder?
See my code below. I'm hoping that I can change the header or content type and get this to work. I'm open to any coding suggestions. As I said, our client is not going to change security options on their and their clients' machines; this needs to be something I can do in the code so the client doesn't have to do anything. Also, my boss is very hesitant to give me time to learn 3rd party controls so those are probably out as well.
var grid = new DataGrid();
grid.HeaderStyle.Font.Bold = true;
grid.AlternatingItemStyle.BackColor = System.Drawing.Color.DarkGray;
grid.DataSource = GetTable(storerId, bSunday, bMonday, bTuesday, bWednesday, bThursday, bFriday, bSaturday, beginDate, endDate);
grid.DataBind();
response.Clear();
//response.AddHeader("content-disposition", string.Format("{0}{1}{2}{3}{4}", "attachment;filename=", storerId, "KpiExport", DateTime.Today.ToShortDateString(), ".xls"));
//response.AddHeader("Content-Disposition", string.Format("{0}{1}{2}{3}{4}", "attachment;filename=", storerId, "KpiExport", DateTime.Today.ToShortDateString(), ".xls"));
HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "sample.xls"));
response.Charset = "";
// response.ContentType = "application/vnd.xls";
response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
var writer = new StringWriter();
var htmlWriter = new HtmlTextWriter(writer);
grid.RenderControl(htmlWriter);
response.Write(writer.ToString());
response.End();
I have to Provide the functionality to export all the data shown in repeater to excel file. I have successfully done that but the file size goes above 4MBs.
Here is the code I am using.
public void ExportToExcel(Repeater name)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=RepeaterExport.csv");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
Repeater rp = name;
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
foreach (RepeaterItem item in name.Items)
{
item.Controls.Remove(item.FindControl("hd_Depot"));
item.Controls.Remove(item.FindControl("hd_ProdCode"));
item.Controls.Remove(item.FindControl("hd_Closing"));
item.Controls.Remove(item.FindControl("hd_groupName"));
}
rp.RenderControl(hw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
Now when I use xls or xlsx it downloads perfectly but with large size but if I use csv it writes the whole html code to excel file. my main motive here is to shrink the size of the excel file to less than 1MB. Please advise.
It looks like you write an HTML or CSV file and pretends it is an Excel sheet in the Content-Type so that it opens with Excel. A better solution is to create a real Excel sheet, i.e. with an xlsx extension, using some library that can do this for you.
I think the xlsx contains the entire html, and that's why it's so big.
If you just want to export to csv:
create a string which contains the data (in your for loop)
Contenttype is: "text/csv"
I use a kbCSV and the CSVWriter.
I am trying to export a gridview's contents to excel. I have some code:
public void ExcelDownload(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.Charset = "UTF-8";
Response.AppendHeader("Content-Disposition", "attachment;filename=MailingList.xls");
Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
Response.ContentType = "application/ms-excel";
this.EnableViewState = false;
System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("EN-US", true);
System.IO.StringWriter oStringWriter = new System.IO.StringWriter(myCItrad);
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
MailingList.RenderControl(oHtmlTextWriter);
Response.Write(oStringWriter.ToString());
}
which runs when a link is clicked. This works fine, except that it is exporting the entire webpage, instead of just the gridview (MailingList). Does anyone know how to fix this?
Tehnically speaking this is not export to excel, but you send a html with a wrong headers to trick browser to open this content with excel. If you stick with this solution you have to render just GridView on separate aspx page.
This solution has may problems, excel it self will warn user that content is different from extension, becouse you send html and your response headers are saying that this is a excel file. And I can bet that some antimalware software on client or something similar on server, will block this response since serving different content than declared in headers is known malware behaviour.
Better use NPOI (xls) or / and EPPlus (xlsx) and fully control your excel export.
I am trying to export the HTML page contents to Word.
My Html display page is:
What is your favourite color?
NA
List the top three school ?
one National
two Devs
three PS
And a button for click event. The button click event will open MS word and paste the page contents in word.
The word page contains the table property of html design page. It occurs only in Word 2003. But in word 2007 the word document contains the text with out table property. How can I remove this table property in word 2003.
I am not able to add the snapshots. Else i will make you clear.
I am designing the web page by aspx. I am exporting the web page content by the following code.
protected void Button1_Click(object sender, EventArgs e)
{
Response.ContentEncoding = System.Text.Encoding.UTF7;
System.Text.StringBuilder SB = new System.Text.StringBuilder();
System.IO.StringWriter SW = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlTW = new System.Web.UI.HtmlTextWriter(SW);
tbl.RenderControl(htmlTW);
string strBody = "<html>" +
"<body>" + "<div><b>" + htmlTW.InnerWriter.ToString() + "</b></div>" +
"</body>" +
"</html>";
Response.AppendHeader("Content-Type", "application/msword");
Response.AppendHeader("Content-disposition", "attachment; filename=" + fileName);
Response.ContentEncoding = System.Text.Encoding.UTF7;
string fileName1 = "C://Temp/Excel" + DateTime.Now.Millisecond.ToString();
BinaryWriter writer = new BinaryWriter(File.Open(fileName1, FileMode.Create));
writer.Write(strBody);
writer.Close();
FileStream fs = new FileStream(fileName1, FileMode.Open, FileAccess.Read);
byte[] renderedBytes;
// Create a byte array of file stream length
renderedBytes = new byte[fs.Length];
//Read block of bytes from stream into the byte array
fs.Read(renderedBytes, 0, System.Convert.ToInt32(fs.Length));
//Close the File Stream
fs.Close();
FileInfo TheFile = new FileInfo(fileName1);
if (TheFile.Exists)
{
File.Delete(fileName1);
}
Response.BinaryWrite(renderedBytes);
Response.Flush();
Response.End();
}
You are writing HTML, claiming it is of content type "application/msword", then hoping for the best..
There are more "correct" ways to achieve your objective.
There are a few projects around for converting (X)HTML to WordML content, of which docx4j-ImportXHTML.NET is one. Disclosure: I maintain that; you can find links to others elsewhere here on StackOverflow.
Alternatively, you can use Word's altChunk mechanism, though note:
you have less control over how the import is performed;
AltChunk isn't supported by Word 2003 (even with the compatibility pack).
Question not clear.
Well, these links may help you in understanding MSWord-C# automation:
http://www.codeproject.com/KB/cs/Simple_Ms_Word_Automation.aspx
http://www.c-sharpcorner.com/UploadFile/amrish_deep/WordAutomation05102007223934PM/WordAutomation.aspx
You can also try to create an Open XML document that is now recognized by MS office.
Here is some more info with code samples:
http://msdn.microsoft.com/en-us/library/bb656295.aspx
From what I understand, you are trying to create a ms word document on the fly and are having difficulty when the output is viewed in Word 2003 vs. 2007.
In your code above, you are simply spitting out html and forcing it to be a ms word document. I'm surprised it even works.
Instead, you might want to use Office Interop (Microsoft.Office.Interop.Word) or install DocX using nuget. Look at some examples online, search for "C# create word doc".