I was developing a small ASP.NET app and was trying to open an excel file in the browser. After a couple of attempts, I discovered that I was specifying the incorrect MIME type. Upon using the following code I was able to get the excel file to open in the browser:
string fileName = Server.MapPath("HelloWorld.xls");
Response.ContentType = "application/vnd.ms-excel";
Response.WriteFile(fileName);
However, this was opening the file in the same webpage and the back button was not having the desired effect of moving back to the initial page. After some attempts I found a simple way to get that to work correctly:
I declared a class
public class ExcelFile
{
public static string excelFileName;
}
set the static variable to the required filename, redirected the output to another page and used the same code in the page_load event:
private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
Response.ContentType = "application/vnd.ms-excel";
Response.WriteFile(ExcelFile.excelFileName);
}
No comments:
Post a Comment