What are the alternative ways to export excel file - c#

i m trying to generate an excel file from my web page but i have some issues with Turkish chars such as "İ" "ğ" when i open the file some chars are incorrect (İ seems Ä°) here is my code
gvExpRequests.DataSource = dsExpRequests;
gvExpRequests.DataBind();
gvExpRequests.GridLines = GridLines.Both;
Page.EnableViewState = false;
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=export.xls");
Response.ContentType = "application/ms-excel";
Response.ContentEncoding = Encoding.UTF8;
Response.BinaryWrite(Encoding.UTF8.GetPreamble());
StringWriter yaz = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(yaz);
gvExpRequests.RenderControl(htw);
i don't know what's wrong with here i tried a lot of encoding but i got same results every time i want to try something different to do this are there any another way to export a excel file from a gridview

Related

WebForm Server.Transfer - Variables are not being recorded in downloaded files

I'm using Server.Transfer and in the 2nd place I have a number of labels that are updated with a Request.Form["textbox_text"];
This all works really well, but the problem is I also want to write the content in that textbox to file
like a word document using this method
Response.Clear();
Response.AddHeader("Content-disposition", "attachment; filename=Word.doc");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application / vnd.ms -word";
Response.ContentEncoding = System.Text.Encoding.Unicode;
Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
htw.Write("<table><h2><b>[ Text ]</b></h2><br>" + TextBox_name.Text + "</table>");
Response.Write(sw.ToString());
Response.End();
But whenever I check the file it will not have anything written on it. I've even tried to save the value of a Request.Form to a static variable and then write that variable but without any success.
How are you using Server.Transfer()? Post that code, make sure you are using the overload that preserves the form values:
Server.Transfer("page.aspx", true);

Saved Excel Can't Be opened with Excel 2016

I'm using the following code to generate an Excel file
private void ExportGridView(GridView gv)
{
string attachment = "attachment; filename=Factuurtjes.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
// Create a form to contain the grid
HtmlForm frm = new HtmlForm();
gv.Parent.Controls.Add(frm);
//Response.Write("Opdrachtgever geselecteerd: " + ddlContractor.SelectedItem.ToString());
frm.Attributes["runat"] = "server";
frm.Controls.Add(gv);
frm.RenderControl(htw);
//GridView1.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
This all works fine and the excel file gets saved as it should.
I can open the excel file with excel 2013. But when I want to open it with Excel 2016, it gives me a warning message that the file could be damaged.
I would like a solution for this so I can open the files with Excel 2016.
Can someone help me with this?
Thanks in advance.
I think this Save-an-Excel-2016-workbook-for-compatibility-with-earlier-versions-of-Excel can help to solve your problem.

Generate and Save file to database

I have a record set (DataTable) that I am saving to Excel and then need to save to a database (as binary).
I have two parts working separately, but I can't figure out how to tie them both together without having to actually save a hard copy of the Excel to the disk.
Here is the "export to Excel" code:
string attachment = "attachment; filename=" + filename;
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gvCompleteCases.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
and the "save file to database" snippet:
byte[] fileData = null;
using (var binaryReader = new BinaryReader(file.InputStream))
{
fileData = binaryReader.ReadBytes(file.ContentLength);
UploadFile.Upload2(GetD(), file.ContentLength, fu.FileBytes, numberOfPages);
}
The above example saves the file to user's machine and then I have to point to its location to save to the database, is there a way I can create the Excel file, without saving to user's hard disk, before saving it to the database?
I guess what I'm asking is how do I get the fileData of the created Excel, without saving it to the computer?

Stop Date Auto-Format when Exporting from DataGrid to Excel in C#

I am currently formatting a Date for a specific Excel file Export from a DataSet/DataGrid.
The Date is formatted like so:
DateTime date = Convert.ToDateTime(entry.Date);
string formatdate = String.Format("{0:yyyy/MM/dd}", date);
Once creating the DataSet is said and done, I use the following code to Export the DataSet to an Excel file:
public static void ExportDStoExcel(DataSet ds, string filename)
{
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.Charset = "";
response.ContentType = "application/vnd.ms-excel";
response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
DataGrid dg = new DataGrid();
dg.DataSource = ds.Tables[0];
dg.DataBind();
dg.RenderControl(htw);
response.Write(sw.ToString());
response.End();
}
}
}
My only problem is once I export this to Excel, Excel Auto-Formats the Dates like this: MM/DD/YYYY instead of YYYY/MM/DD.
I understand this could be achieved manually by opening in Excel, but the Export is being built into an Automated System and needs to be hard coded.
Is there any way of bypassing Excel's DateTime Auto-Formatting?
I had the same issue and solved it by adding a non breaking space (&nbsp) in front of the text. Stopped Excel from auto-formatting. Not the cleanest solution but did the trick for me...
Right now you are just outputting HTML table, that Excel interprets how it likes. You'd have bring yourself down to Excel's level to be able to specify column's properties (set type to Text instead of General).
This means that you need to generate actual xls file (there are various libraries out there for that). Or (if restriction to Office 2010 is acceptable) got with Open XML format which you can write with regular .NET API.
You can style excel cells with mso-number-format
mso-number-format:"\\#"
\# will tell excel to treat all data in text format only. So auto format won't happen.
Please update your code like this:
response.ContentType = "application/vnd.ms-excel";
response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
response.Write("<html xmlns:x=\"urn:schemas-microsoft-com:office:excel\">");
response.Write("<head><style> td {mso-number-format:\\#;} </style></head><body>");
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
DataGrid dg = new DataGrid();
dg.DataSource = ds.Tables[0];
dg.DataBind();
dg.RenderControl(htw);
response.Write(sw.ToString());
response.Write("</body></html>");
response.End();
}
}
OR
you can try with specific date format also.
Refer: http://cosicimiento.blogspot.in/2008/11/styling-excel-cells-with-mso-number.html
mso-number-format:"yyyy\/mm\/dd"

Save the generated pdf directly to the server directory folder without user prompt

A friend of mine gave me this task so I can learn advance programming a little bit easier. I am currently doing convertion of an html page to pdf using itext sharp and email the pdf as an attachement. My idea is to save the pdf first to the server machine in the folder name ToBeEmailedPDF folder before using it as an email attachment. The thing that bothers me is that this dialog as what you can see in the picture shows up using the code that I have below.
StringBuilder sb = new StringBuilder();
StringWriter tw = new StringWriter(sb);
HtmlTextWriter hw = new HtmlTextWriter(tw);
pnlPDF.RenderControl(hw); // pnlPDF contains the html contents to be converted to pdf
string htmlDisplayText = sb.ToString();
Document document = new Document();
MemoryStream ms = new MemoryStream();
PdfWriter writer = PdfWriter.GetInstance(document, ms);
StringReader se = new StringReader(htmlDisplayText);
HTMLWorker obj = new HTMLWorker(document);
document.Open();
obj.Parse(se);
// step 5: we close the document
document.Close();
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=report.pdf");
Response.ContentType = "application/pdf";
Response.Buffer = true;
Response.OutputStream.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
Response.OutputStream.Flush();
Response.End();
I know many of you out there knows a better way or know how to solve my problem. Please help me. Thank you!
There is big difference between client-side and server-side.
Response class can output contents to client machine, if you need to save file on server use something like File.WriteAllBytes (msdn) method
What you are trying to achieve is impossible for security reasons. Only the user can decide where he wants the attachment to be saved. Imagine if this was possible: you would then be able to save any kind of viruses into any kind of folders on the user's computer. As an alternative to showing the Save dialog you could open the PDF inline:
Response.AddHeader("Content-Disposition", "inline; filename=report.pdf");
You can save it using the following code:
PdfWriter.GetInstance(pdfDoc, new FileStream(context.Server.MapPath("~") + "/PDF/" + reportName + ".pdf", FileMode.Create));

Categories