Open Word Excel PDF PowerPoint (PPT) files in new browser window in ASP.Net

Last Reply on Feb 28, 2016 08:53 AM By rani

Posted on Feb 28, 2016 02:07 AM

Below is the page and file is in local drive.

<asp:GridView runat="server" ID="gvDetails" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="Id" HeaderText="Id" />
        <asp:BoundField DataField="Name" HeaderText="Name" />
        <asp:BoundField DataField="FilePath" HeaderText="File Path" />
        <asp:TemplateField>
            <ItemTemplate>
                <asp:HyperLink ID="lnkView" Text="View" NavigateUrl='<%# string.Format("~/Popup.aspx?Id={0}&FilePath={1}", Eval("Id").ToString(), Eval("FilePath").ToString()) %>'
                    runat="server" />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>
    Id     Name        File Path  
1 Resume.jpg D:\Personal\Resume.jpg View
2 Resume.docx D:\Personal\Resume.docx View
3 Resume.pdf D:\Personal\Resume.pdf View
3 Resume.xls D:\Personal\Resume.xls View

How can i display these files in web browser with a new popup window.

With reference with some article in aspsnippet I am able to display word image pdf file in browser and now my requirement is how to display excel file in browser and also all these in new popup window not in the same page?

protected void Page_Load(object sender, EventArgs e)
{        
    string filePath = Request.QueryString["FilePath"];
    string fileExtension = filePath.Split('.')[filePath.Split('.').Length - 1];
    string fileName = filePath.Split('\\')[filePath.Split('\\').Length - 1];
    switch (fileExtension.ToLower())
    {
        case "pdf":
            Response.ContentType = "Application/pdf";
            break;
        case "doc":
            writeWordFile(filePath);
            break;
        case "docx":
            writeWordFile(filePath);
            break;
        case "xls":
            Response.ContentType = "Application/x-msexcel";
            break;
        case "xlsx":
            Response.ContentType = "Application/pdf";
            break;
        case "jpg":
            Response.ContentType = "image/JPEG";
            break;
        case "gif":
            Response.ContentType = "image/GIF";
            break;
        default:
            break;
    }

    Response.WriteFile(filePath);
    Response.End();
}

private void writeWordFile(object filePath)
{
    object missingType = Type.Missing;
    object readOnly = true;
    object isVisible = false;
    object documentFormat = 8;
    string randomName = DateTime.Now.Ticks.ToString();
    object htmlFilePath = Server.MapPath("~/Temp/") + randomName + ".htm";
    string directoryPath = Server.MapPath("~/Temp/") + randomName + "_files";
    ApplicationClass applicationclass = new ApplicationClass();
    applicationclass.Documents.Open(ref filePath,
                                    ref readOnly,
                                    ref missingType, ref missingType, ref missingType,
                                    ref missingType, ref missingType, ref missingType,
                                    ref missingType, ref missingType, ref isVisible,
                                    ref missingType, ref missingType, ref missingType,
                                    ref missingType, ref missingType);
    applicationclass.Visible = false;
    Document document = applicationclass.ActiveDocument;
    document.SaveAs(ref htmlFilePath, ref documentFormat, ref missingType,
                    ref missingType, ref missingType, ref missingType,
                    ref missingType, ref missingType, ref missingType,
                    ref missingType, ref missingType, ref missingType,
                    ref missingType, ref missingType, ref missingType,
                    ref missingType);
    document.Close(ref missingType, ref missingType, ref missingType);
    byte[] bytes;
    using (FileStream fs = new FileStream(htmlFilePath.ToString(), FileMode.Open, FileAccess.Read))
    {
        BinaryReader reader = new BinaryReader(fs);
        bytes = reader.ReadBytes((int)fs.Length);
        fs.Close();
    }
    Response.BinaryWrite(bytes);
    Response.Flush();
    File.Delete(htmlFilePath.ToString());
    foreach (string file in Directory.GetFiles(directoryPath))
    {
        File.Delete(file);
    }
    Directory.Delete(directoryPath);
}

Any help will appreciate.

 

You are viewing reply posted by: rani on Feb 28, 2016 08:53 AM.
Posted on Feb 28, 2016 08:53 AM

Thanks Andrea for your reply. But now i am able to solve it by this way.

Default page

<asp:GridView runat="server" ID="gvDetails" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="Id" HeaderText="Id" />
        <asp:BoundField DataField="Name" HeaderText="Name" />
        <asp:BoundField DataField="FilePath" HeaderText="File Path" />
        <asp:TemplateField>
            <ItemTemplate>
                <asp:HyperLink ID="lnkView" Text="View" NavigateUrl='<%# string.Format("~/Popup.aspx?Id={0}&FilePath={1}", Eval("Id").ToString(), Eval("FilePath").ToString()) %>'
                    runat="server" Target="_blank" />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

code

DataTable dt = new DataTable();
dt.Columns.Add("Id");
dt.Columns.Add("Name");
dt.Columns.Add("FilePath");
dt.Rows.Add("1", "Resume.jpg", @"D:\Personal\Resume.jpg");
dt.Rows.Add("2", "Resume.docx", @"D:\Personal\Resume.docx");
dt.Rows.Add("3", "Resume.pdf", @"D:\Personal\Resume.pdf");
dt.Rows.Add("4", "Resume.xls", @"D:\Personal\Resume.xls");
gvDetails.DataSource = dt;
gvDetails.DataBind();

popup page

<asp:GridView runat="server" ID="displayExcel" />

code

protected void Page_Load(object sender, EventArgs e)
{
    if (Request.QueryString["FilePath"] != null || Request.QueryString["FilePath"] != string.Empty)
    {
        string filePath = Request.QueryString["FilePath"];
        string fileExtension = filePath.Split('.')[filePath.Split('.').Length - 1];
        string fileName = filePath.Split('\\')[filePath.Split('\\').Length - 1];
        switch (fileExtension.ToLower())
        {
            case "pdf":
                Response.ContentType = "Application/pdf";
                Response.WriteFile(filePath);
                Response.End();
                break;
            case "jpg":
                Response.ContentType = "image/JPEG";
                Response.WriteFile(filePath);
                Response.End();
                break;
            case "gif":
                Response.ContentType = "image/GIF";
                Response.WriteFile(filePath);
                Response.End();
                break;
            case "doc":
                writeWordFile(filePath);
                break;
            case "docx":
                writeWordFile(filePath);
                break;
            case "xls":
                displayExcel.DataSource = writeExcelFile(filePath, "xls"); ;
                displayExcel.DataBind();
                break;
            case "xlsx":
                displayExcel.DataSource = writeExcelFile(filePath, "xlsx"); ;
                displayExcel.DataBind();
                break;
            default:
                break;
        }
    }
}

private void writeWordFile(object filePath)
{
    object missingType = Type.Missing;
    object readOnly = true;
    object isVisible = false;
    object documentFormat = 8;
    string randomName = DateTime.Now.Ticks.ToString();
    object htmlFilePath = Server.MapPath("~/Temp/") + randomName + ".htm";
    string directoryPath = Server.MapPath("~/Temp/") + randomName + "_files";
    ApplicationClass applicationclass = new ApplicationClass();
    applicationclass.Documents.Open(ref filePath,
                                    ref readOnly,
                                    ref missingType, ref missingType, ref missingType,
                                    ref missingType, ref missingType, ref missingType,
                                    ref missingType, ref missingType, ref isVisible,
                                    ref missingType, ref missingType, ref missingType,
                                    ref missingType, ref missingType);
    applicationclass.Visible = false;
    Document document = applicationclass.ActiveDocument;
    document.SaveAs(ref htmlFilePath, ref documentFormat, ref missingType,
                    ref missingType, ref missingType, ref missingType,
                    ref missingType, ref missingType, ref missingType,
                    ref missingType, ref missingType, ref missingType,
                    ref missingType, ref missingType, ref missingType,
                    ref missingType);
    document.Close(ref missingType, ref missingType, ref missingType);
    byte[] bytes;
    using (FileStream fs = new FileStream(htmlFilePath.ToString(), FileMode.Open, FileAccess.Read))
    {
        BinaryReader reader = new BinaryReader(fs);
        bytes = reader.ReadBytes((int)fs.Length);
        fs.Close();
    }
    Response.BinaryWrite(bytes);
    Response.Flush();
    File.Delete(htmlFilePath.ToString());
    foreach (string file in Directory.GetFiles(directoryPath))
    {
        File.Delete(file);
    }
    Directory.Delete(directoryPath);
    Response.End();
}

private DataSet writeExcelFile(string filePath, string extension)
{
    System.Data.DataTable dtExcel = new System.Data.DataTable();
    string str = string.Empty;
    if (extension.ToLower() == "xls")
    {
        str = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties='Excel 8.0;HDR=Yes'";
    }
    else if (extension.ToLower() == "xlsx")
    {
        str = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties='Excel 8.0;HDR=Yes'";
    }

    OleDbConnection con = new OleDbConnection(str);
    OleDbCommand cmdExcel = new OleDbCommand();
    cmdExcel.Connection = con;
    con.Open();
    dtExcel = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
    con.Close();
    con.Open();
    OleDbDataAdapter da = new OleDbDataAdapter();
    DataSet ds = new DataSet();
    string SheetName = dtExcel.Rows[0]["TABLE_NAME"].ToString();
    cmdExcel.CommandText = "SELECT * FROM [" + SheetName + "]";
    da.SelectCommand = cmdExcel;
    da.Fill(ds);
    con.Close();
    return ds;
}