Home > Code > C# > Open an existing Excel file using C#.NET

Open an existing Excel file using C#.NET

by Narain_Siddharth   on May 22, 2011   Category: C#   |  Views: 1132    |  Points: 25   |  Silver 



Below c# code shows how to open the existing excel file from particular folder.


using System;
using System.Text;
using System.IO;

protected void BtnOpen_Click(object sender, EventArgs e)
{
try
{
string XlsPath = Server.MapPath(@"~/Add_data/test.xlsx");
FileInfo fileDet = new System.IO.FileInfo(XlsPath);
Response.Clear();
Response.Charset = "UTF-8";
Response.ContentEncoding = Encoding.UTF8;
Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(fileDet.Name));
Response.AddHeader("Content-Length", fileDet.Length.ToString());
Response.ContentType = "application/ms-excel";
Response.WriteFile(fileDet.FullName);
Response.End();
}
catch (Exception ex)
{
throw ex;
}
}




Like this code? Bookmark and Share:

  User Responses | Post Code
Comment posted by Raja on 23/05/2011 | Points : 5
This is what i'm looking... thank you.
Comment posted by Akkineni2009 on 20/07/2011 | Points : 5
This code helps. And i tried to use it in my application as i need to open the excel spreed sheet.

But when i use this code it is openiing the file but not displaying as excel spreed sheet.
it open as if we open the spread sheet into notepad or text pad.
Any help on what the Response.charset should be?
Comment posted by Akkineni2009 on 20/07/2011 | Points : 5
Actually, I removed the two lines for the code
Response.Charset = "UTF-8";
Response.ContentEncoding = Encoding.UTF8;

it is now working.

This is a great help
Thanks to Narain Siddharth
  Recent Posts
* Setting focus to textbox control using JavaScript (308) by Narain_Siddharth on Nov 13 2010 11:25AM
* Sending Mails with Attachements using Asp.Net (362) by Narain_Siddharth on Nov 13 2010 11:48AM
* Disable the Submit button when insert or update a record using JavaScript (278) by Narain_Siddharth on Nov 13 2010 12:31PM
* String comparisons using C#.NET string.compareTo (289) by Thamilselvanj on Nov 14 2010 11:16AM
* String.Split using C# (287) by Thamilselvanj on Nov 14 2010 11:23AM
  Submit feedback about this code snippet
Please sign in to post feedback