Saved Excel Can't Be opened with Excel 2016 - c#

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.

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);

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?

How to avoid downloading files to the download folder and download to other specific folder only in c#

I am trying to convert the gridview to excel and downloading the excel sheet to my computer's specific folder in my c# application.
The problem is: The file is getting downloaded at both the places.The destination folder and also the download folder.
the code for this is:
private void ExportToExcel(GridView GrdView, string fname)
{
Response.Clear();
Response.AddHeader("content-disposition", "inline;filename=" + fname + ".xls");
Response.Charset = "";
Response.ContentType = "application/OCTET-STREAM";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite =
new HtmlTextWriter(stringWrite);
GridView1.RenderControl(htmlWrite);
string renderedGridView = stringWrite.ToString();
File.WriteAllText(#"C:\\Users\abc\\Desktop\" + fname + ".xls", renderedGridView);
Response.Write(stringWrite.ToString());
Response.End();
}
How to avoid the files getting downloaded to the download folder?
Please help!
Thank you
The answer would be to pick one: either render the control to a string and output to Response OR WriteAllText. If you want to use the WriteAllText to save the file to a determined location, then perform the action and pop up a notification to the user that the file was saved.

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"

What are the alternative ways to export excel file

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

Categories