Saturday 26 May 2012

Word Documents and Excel Documents in IFRAME

In this below example we are converting word OR excel document to HTML.

In this case we are converting and giving converted HTML file as ""src"" to ""iframe"".

Step By Step Procedure :

1)First step is create one folder in your application which needs to maintain the documents in that because iframe will take src within the application itself,outside of the application it will not work.

2) The aspx page as follows :

    <asp:ScriptManager ID="ScriptManager2" runat="server">
    </asp:ScriptManager>
    <div>
        <table>
            <tr>
                <td valign="middle" align="center">
                    <asp:FileUpload ID="FileUpload2" runat="server" />
                    <asp:Button ID="btnView" runat="server" Text="View" onclick="btnView_Click" />
                </td>
            </tr>
            <tr>
                <td width="100%">
                    <asp:UpdatePanel ID="panel2" runat="server">
                        <ContentTemplate>
                            <div style="background-color: ThreeDFace;">
                                <asp:Label ID="lblFileName" runat="server">
                                </asp:Label>
                            </div>
                            <br />
                            <iframe id="docPreview" src="" width="100%" height="500px" frameborder="0" runat="server">
                            </iframe>
                        </ContentTemplate>
                    </asp:UpdatePanel>
                </td>
            </tr>
        </table>
    </div>


3) Add Interop.Excel & Interop.Word dll references for the application :



4) The button click event will be like this :

First get the binary data of file and save that file to its original format in documents folder.After saving the file according to the file extension convert to Html format and give the Html file as src for iframe.

private Word.ApplicationClass MSWord;       // The Interop Object for Word
private Excel.ApplicationClass MSExcel;     // The Interop Object for Excel
object Unknown = Type.Missing;        // For passing Empty values
protected void Page_Load(object sender, EventArgs e)
{
           
}

protected void btnView_Click(object sender, EventArgs e)
{
            byte[] BinaryFile = null;
            if (FileUpload2.PostedFile != null)
            {
                int FileSize = FileUpload2.PostedFile.ContentLength;
                BinaryFile = new byte[FileSize];
                FileUpload2.PostedFile.InputStream.Read(BinaryFile, 0, (int)FileUpload2.PostedFile.ContentLength);
                string FileName = FileUpload2.FileName;
                lblFileName.Text = FileName;
                string FileExtension = Path.GetExtension(FileName);
                string FolderPath = Server.MapPath("~/Documents");
                File.WriteAllBytes(FolderPath + "\\" + FileName, BinaryFile);
                if (FileExtension == ".doc" || FileExtension == ".docx")
                {
                    ConvertWordToHTML(FolderPath + "\\" + FileName, FolderPath + "\\" + FileName.Split('.')[0] + ".html");
                }
                else if (FileExtension == ".xls" || FileExtension == ".xlsx")
                {
                    ConvertExcelToHTML(FolderPath + "\\" + FileName, FolderPath + "\\" + FileName.Split('.')[0] + ".html");
                }
                docPreview.Attributes["src"] = "../Documents/" + FileName.Split('.')[0] + ".html";
            }
}

This method is used to convert WordDocument to HTML :

public void ConvertWordToHTML(object FilePath, object SaveTarget)
{
            if (MSWord == null)
                MSWord = new Word.ApplicationClass();

            try
            {
                MSWord.Visible = false;
                MSWord.Application.Visible = false;
                MSWord.WindowState = Word.WdWindowState.wdWindowStateMinimize;

                MSWord.Documents.Open(ref FilePath, ref Unknown,
                     ref Unknown, ref Unknown, ref Unknown,
                     ref Unknown, ref Unknown, ref Unknown,
                     ref Unknown, ref Unknown, ref Unknown,
                     ref Unknown, ref Unknown, ref Unknown, ref Unknown);

                object format = Word.WdSaveFormat.wdFormatHTML;

                MSWord.ActiveDocument.SaveAs(ref SaveTarget, ref format,
                        ref Unknown, ref Unknown, ref Unknown,
                        ref Unknown, ref Unknown, ref Unknown,
                        ref Unknown, ref Unknown, ref Unknown,
                        ref Unknown, ref Unknown, ref Unknown,
                       ref Unknown, ref Unknown);
            }
            catch (Exception e)
            {
            }
            finally
            {
                if (MSWord != null)
                {
                    MSWord.Documents.Close(ref Unknown, ref Unknown, ref Unknown);
                    MSWord.Quit(ref Unknown, ref Unknown, ref Unknown);
                }
            }
}

This method is used to convert ExcelDocument to HTML :

public void ConvertExcelToHTML(string Source, string Target)
{
            if (MSExcel == null) 
                MSExcel = new Excel.ApplicationClass();

            try
            {
                MSExcel.Visible = false;
                MSExcel.Application.Visible = false;
                MSExcel.WindowState = Excel.XlWindowState.xlMinimized;

                MSExcel.Workbooks.Open(Source, Unknown,
                     Unknown, Unknown, Unknown,
                     Unknown, Unknown, Unknown,
                     Unknown, Unknown, Unknown,
                     Unknown, Unknown, Unknown, Unknown);

                object format = Excel.XlFileFormat.xlHtml;

                MSExcel.Workbooks[1].SaveAs(Target, format,
                        Unknown, Unknown, Unknown,
                        Unknown, Excel.XlSaveAsAccessMode.xlExclusive, Unknown,
                        Unknown, Unknown, Unknown,
                        Unknown);
            }
            catch (Exception e)
            {
            }
            finally
            {
                if (MSExcel != null)
                {
                    MSExcel.Workbooks.Close();
                    MSExcel.Quit();
                }
            }
}

5) Here in my example i have taken fileupload to upload word and excel documents, after selecting a file by clicking View button we can view the output just like this :

Output for WordDocument :



Output for ExcelDocument :





7 comments:

  1. This comment has been removed by a blog administrator.

    ReplyDelete
  2. nice example

    how to fix this error?
    '"Namespace".File' does not contain a definition for 'WriteAllBytes'

    ReplyDelete
    Replies
    1. sry for the delay
      your problem will be solved by "System.IO" NameSpace please check that one and let me know

      Delete
  3. sorry.
    Exception from HRESULT: 0x80028018 (TYPE_E_INVDATAREAD)
    send me error...
    Lobo_C@hotmail.com

    ReplyDelete
    Replies
    1. If u don't mind can u give some clear about where you are getting this error

      Delete
  4. This method perfectly working with in source code. when we host or deploy in iis6 (or) above and windows 2007 its not working. for that we have to make many changes on server system. Interop.Word better to avoid. instead of that
    we can use OpenXml methods. But these method works with .docx methods only

    ReplyDelete