ARTICLE AD BOX
I am using this C# code to generate the an Excel file from my app, and it worked fine when the .xls file is generated, but when I changed it to .xlsx, now I get an error shown in the title when trying to open the file. The file is not empty because the size is 5 KB.
This is my code:
public void ExportToExcel(string name, DataTable dt) { lock (this) { System.Text.StringBuilder tmp = new System.Text.StringBuilder(1000000); for (int i = 0; i < rt.Columns.Count; i++) { string colname = rt.Columns[i].ColumnName; if (i < rt.Columns.Count - 1) { tmp.Append(colname + "\t"); } else { tmp.Append(colname + "\t\r\n"); } } foreach (DataRow r in rt.Rows) { for (int i = 0; i < r.ItemArray.Length; i++) { if (i < r.ItemArray.Length - 1) { tmp.Append((r.ItemArray.GetValue(i)) + "\t"); } else { string status = r.ItemArray.GetValue(i).ToString(); int indexS = status.IndexOf(">", 0); int indexE = 0; string subStatus = ""; if (indexS > 0) { indexE = status.IndexOf("<", indexS); subStatus = status.Substring(indexS + 1, indexE - indexS - 1); tmp.Append(subStatus + "\t\r\n"); } else { tmp.Append(status + "\t\r\n"); } } } } sw.WriteLine(tmp.ToString()); sw.Flush(); sw.Close(); byte[] byteArray = fileStream.ToArray(); fileStream.Flush(); fileStream.Close(); DateTime dtToday = DateTime.Now; string date = dtToday.ToString("MM-dd-yyyy HH:mm:ss"); Response.Clear(); Response.Charset = ""; //Response.ContentType = "application/vnd.ms-excel"; Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; Response.AddHeader("Content-Length", byteArray.Length.ToString()); //Response.AddHeader("Content-Disposition", "attachment; filename=" + name + "_" + date + ".xls"); Response.AddHeader("Content-Disposition", "attachment; filename=" + name + "_" + date + ".xlsx"); Response.BinaryWrite(byteArray); Response.End(); //Session[name] = null; } }I did changed the Response.ContentType from application/vnd.ms-excel to application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.
Any help is appreciated.
761k186 gold badges1.4k silver badges1.5k bronze badges
5
Explore related questions
See similar questions with these tags.
