asp.net實現word文件線上檢視功能 (三種方法)

huangwenhua5000發表於2012-12-27

1.通過javascript開啟\編輯\根據模板新建word文件          

           //"SharePoint.OpenDocuments.1"可與Office XP相容
            var openDocObj = new ActiveXObject("SharePoint.OpenDocuments.2");
          
            //開啟文件
            openDocObj.ViewDocument(lUrl+"./documents/sample.doc");

            //ViewDocument()方法還有一個過載簽名,可以讓我們手工指定啟用哪個程式來開啟文件:    
            openDocObj.ViewDocument(lUrl+"./documents/sample.doc",   要啟用的程式的ProgID); 

            //編輯文件
            var lUrl = window.location.href;
            openDocObj.EditDocument(lUrl+"./documents/sample.doc");
          
            //根據模板建立文件(模板,新文件儲存路徑)
            openDocObj.CreateNewDocument(lUrl+"./documents/sampleTemplate.dot", lUrl+"./documents/");

 

注:iis必須設定為可寫,web服務擴充套件中的WebDaV應是允許狀態

2.直接把檔案上傳進資料庫

string FileName;
        Stream WordStream = SearchFile.PostedFile.InputStream;
        string FilePath = this.SearchFile.PostedFile.FileName;
        FileName = Path.GetFileName(FilePath);
        if (FileName != null && FileName != "")
        {
            int WordLen = SearchFile.PostedFile.ContentLength;
            string WordType = SearchFile.PostedFile.ContentType;
            byte[] WordData = new Byte[WordLen];
            int n = WordStream.Read(WordData, 0, WordLen);
            WordStream.Close();
            SqlCommand com = new SqlCommand();
            com.CommandText = "insert into MyTable(name,FileBinary) values(@FileName,@FileBinary)";
            com.Parameters.Add(new System.Data.SqlClient.SqlParameter("@FileName", System.Data.SqlDbType.Char, 20, "FileName"));
            com.Parameters.Add(new System.Data.SqlClient.SqlParameter("@FileBinary", System.Data.SqlDbType.Image, WordData.Length, "FileBinary"));
            com.Connection = sqlConnection;
            com.Parameters["@FileName"].Value = FileName;
            com.Parameters["@FileBinary"].Value = WordData;
            com.Connection.Open();
            com.ExecuteNonQuery();
            com.Connection.Close();
        }
        else
        {
            Response.Write(" ");
        }

3.資料流的方式在瀏覽器中顯示Word檔案

Response.ContentType = "Application/msword";

        this.Response.Clear();
      
        SqlCommand selcom = new SqlCommand();
        selcom.CommandText = "select name,FileBinary from MyTable order by id desc";
        selcom.Connection = sqlConnection;
        selcom.Connection.Open();
        SqlDataReader dr = selcom.ExecuteReader();
        dr.Read();
        Byte[] b = new Byte[(dr.GetBytes(1, 0, null, 0, int.MaxValue))];
        dr.GetBytes(1, 0, b, 0, b.Length);
        dr.Close();
        selcom.Connection.Close();
        System.IO.Stream fs = this.Response.OutputStream;
        fs.Write(b, 0, b.Length);

        fs.Close();
        this.Response.End();

 

 

 

 

相關文章