2008-09-10 39 views
8

Word 2007 lưu tài liệu của nó ở định dạng .docx, đây thực sự là một tệp nén với một loạt nội dung trong đó bao gồm tệp xml có tài liệu.Làm cách nào để chuyển đổi .docx sang html bằng asp.net?

Tôi muốn có thể lấy tệp .docx và thả tệp vào thư mục trong ứng dụng web asp.net của mình và mở mã tệp .docx và hiển thị tài liệu (phần xml của) trang.

Tôi đã tìm kiếm trên web để biết thêm thông tin về điều này nhưng cho đến nay vẫn chưa tìm thấy nhiều. Câu hỏi của tôi là:

  1. có bạn (a) sử dụng XSLT để chuyển đổi XML sang HTML, hoặc (b) sử dụng thư viện thao tác xml trong .net (như XDocument và XElement trong 3.5) để chuyển đổi sang HTML hoặc (c) khác?
  2. Bạn có biết bất kỳ thư viện/dự án nguồn mở nào đã thực hiện việc này mà tôi có thể sử dụng làm điểm khởi đầu không?

Cảm ơn!

Trả lời

4

Hãy thử điều này post? Tôi không biết nhưng có thể là những gì bạn đang tìm kiếm.

2

Word 2007 có API mà bạn có thể sử dụng để chuyển đổi sang HTML. Đây là một bài viết nói về nó http://msdn.microsoft.com/en-us/magazine/cc163526.aspx. Bạn có thể tìm thấy tài liệu xung quanh API, nhưng tôi nhớ rằng có một hàm chuyển đổi sang HTML trong API.

+0

Bạn có quan tâm cụ thể hơn về API bạn đang nói đến và chức năng "chuyển đổi sang HTML" nào không? Có lẽ bạn đang nói về lớp Package? Chức năng "chuyển đổi sang HTML" ở đâu? – Jez

1

Mã này sẽ giúp chuyển đổi tập tin văn bản .docx

function read_file_docx($filename){ 

    $striped_content = ''; 
    $content = ''; 

    if(!$filename || !file_exists($filename)) { echo "sucess";}else{ echo "not sucess";} 

    $zip = zip_open($filename); 

    if (!$zip || is_numeric($zip)) return false; 

    while ($zip_entry = zip_read($zip)) { 

     if (zip_entry_open($zip, $zip_entry) == FALSE) continue; 

     if (zip_entry_name($zip_entry) != "word/document.xml") continue; 

     $content .= zip_entry_read($zip_entry, zip_entry_filesize($zip_entry)); 

     zip_entry_close($zip_entry); 
    }// end while 

    zip_close($zip); 

    //echo $content; 
    //echo "<hr>"; 
    //file_put_contents('1.xml', $content);  

    $content = str_replace('</w:r></w:p></w:tc><w:tc>', " ", $content); 
    $content = str_replace('</w:r></w:p>', "\r\n", $content); 
    //header("Content-Type: plain/text"); 


    $striped_content = strip_tags($content); 


     $striped_content = preg_replace("/[^a-zA-Z0-9\s\,\.\-\n\r\[email protected]\/\_\(\)]/","",$striped_content); 

    echo nl2br($striped_content); 
} 
0

Tôi đang sử dụng Interop. Nó là hơi gây mê nhưng hoạt động tốt trong hầu hết các trường hợp.

using System.Runtime.InteropServices; 
using Microsoft.Office.Interop.Word; 

Cái này trả về danh sách các html chuyển đổi con đường văn bản

public List<string> GetHelpDocuments() 
    { 

     List<string> lstHtmlDocuments = new List<string>(); 
     foreach (string _sourceFilePath in Directory.GetFiles("")) 
     { 
      string[] validextentions = { ".doc", ".docx" }; 
      if (validextentions.Contains(System.IO.Path.GetExtension(_sourceFilePath))) 
      { 
       sourceFilePath = _sourceFilePath; 
       destinationFilePath = _sourceFilePath.Replace(System.IO.Path.GetExtension(_sourceFilePath), ".html"); 
       if (System.IO.File.Exists(sourceFilePath)) 
       { 
        //checking if the HTML format of the file already exists. if it does then is it the latest one? 
        if (System.IO.File.Exists(destinationFilePath)) 
        { 
         if (System.IO.File.GetCreationTime(destinationFilePath) != System.IO.File.GetCreationTime(sourceFilePath)) 
         { 
          System.IO.File.Delete(destinationFilePath); 
          ConvertToHTML(); 
         } 
        } 
        else 
        { 
         ConvertToHTML(); 
        } 

        lstHtmlDocuments.Add(destinationFilePath); 
       } 
      } 


     } 
     return lstHtmlDocuments; 
    } 

Và một này để chuyển đổi doc sang HTML.

private void ConvertToHtml() 
    { 
     IsError = false; 
     if (System.IO.File.Exists(sourceFilePath)) 
     { 
      Microsoft.Office.Interop.Word.Application docApp = null; 
      string strExtension = System.IO.Path.GetExtension(sourceFilePath); 
      try 
      { 
       docApp = new Microsoft.Office.Interop.Word.Application(); 
       docApp.Visible = true; 

       docApp.DisplayAlerts = WdAlertLevel.wdAlertsNone; 
       object fileFormat = WdSaveFormat.wdFormatHTML; 
       docApp.Application.Visible = true; 
       var doc = docApp.Documents.Open(sourceFilePath); 
       doc.SaveAs2(destinationFilePath, fileFormat); 
      } 
      catch 
      { 
       IsError = true; 
      } 
      finally 
      { 
       try 
       { 
        docApp.Quit(SaveChanges: false); 

       } 
       catch { } 
       finally 
       { 
        Process[] wProcess = Process.GetProcessesByName("WINWORD"); 
        foreach (Process p in wProcess) 
        { 
         p.Kill(); 
        } 
       } 
       Marshal.ReleaseComObject(docApp); 
       docApp = null; 
       GC.Collect(); 
      } 
     } 
    } 

Việc giết từ không vui, nhưng không thể để từ đó treo ở đó và chặn người khác, phải không?

Trong web/html tôi kết xuất html thành khung nội tuyến.

Có một danh sách thả xuống chứa danh sách tài liệu trợ giúp. Giá trị là đường dẫn đến phiên bản html của nó và văn bản là tên của tài liệu.

private void BindHelpContents() 
    { 
     List<string> lstHelpDocuments = new List<string>(); 
     HelpDocuments hDoc = new HelpDocuments(Server.MapPath("~/HelpDocx/docx/")); 
     lstHelpDocuments = hDoc.GetHelpDocuments(); 
     int index = 1; 
     ddlHelpDocuments.Items.Insert(0, new ListItem { Value = "0", Text = "---Select Document---", Selected = true }); 

     foreach (string strHelpDocument in lstHelpDocuments) 
     { 
      ddlHelpDocuments.Items.Insert(index, new ListItem { Value = strHelpDocument, Text = strHelpDocument.Split('\\')[strHelpDocument.Split('\\').Length - 1].Replace(".html", "") }); 
      index++; 
     } 
     FetchDocuments(); 

    } 

trên chỉ số được lựa chọn thay đổi, nó được renedred đóng khung

protected void RenderHelpContents(object sender, EventArgs e) 
    { 
     try 
     { 
      if (ddlHelpDocuments.SelectedValue == "0") return; 
      string strHtml = ddlHelpDocuments.SelectedValue; 
      string newaspxpage = strHtml.Replace(Server.MapPath("~/"), "~/"); 
      string pageVirtualPath = VirtualPathUtility.ToAbsolute(newaspxpage);// 
      documentholder.Attributes["src"] = pageVirtualPath; 
     } 
     catch 
     { 
      lblGError.Text = "Selected document doesn't exist, please refresh the page and try again. If that doesn't help, please contact Support"; 
     } 
    } 
+0

Đó là một ý tưởng khủng khiếp khi sử dụng Office Interop từ ASP.NET hoặc một công nghệ máy chủ khác. Các API này được viết để sử dụng trong một ứng dụng máy tính để bàn, để tự động hóa Office (một bộ ứng dụng máy tính để bàn). Các ứng dụng máy chủ khác nhau theo nhiều cách làm cho nó trở thành một ý tưởng rất, rất tồi khi sử dụng Office Interop trong chúng. Nó cũng không được Microsoft hỗ trợ và có thể vi phạm giấy phép Office của bạn. Xem [Cân nhắc cho Tự động hóa phía máy chủ của văn phòng] (http://support.microsoft.com/kb/257757) –

+0

@JohnSaunders, tôi biết đó là ý tưởng khủng khiếp nhưng các yêu cầu không dễ dàng làm hỏng từ phạm vi. Tôi rất nhiều sẽ đánh giá cao một lựa chọn tốt cho yêu cầu này. –

3

tôi đã viết mammoth.js, mà là một thư viện JavaScript có thể chuyển đổi file docx sang HTML. Nếu bạn muốn thực hiện phía máy chủ dựng hình trong .NET, thì cũng có phiên bản .NET của Mammoth available on NuGet.

Mammoth cố gắng tạo HTML sạch bằng cách xem thông tin ngữ nghĩa - ví dụ, ánh xạ kiểu đoạn trong Word (chẳng hạn như Heading 1) cho các thẻ và kiểu thích hợp trong HTML/CSS (chẳng hạn như <h1>).Nếu bạn muốn một cái gì đó tạo ra một bản sao trực quan chính xác, thì Mammoth có lẽ không phải dành cho bạn. Nếu bạn có thứ gì đó đã được cấu trúc tốt và muốn chuyển đổi nó thành HTML gọn gàng, Mammoth có thể thực hiện thủ thuật.

+0

dotnet-mammoth là một thư viện hữu ích, tôi đang sử dụng nó và hoạt động tốt. Tôi chỉ gặp vấn đề khi triển khai, nếu bạn có thể xem xét nó [ở đây] (http://stackoverflow.com/questions/31885962/converting-docx-to-html-with-dotnet-mammoth-fails-at- triển khai-máy chủ). – zed

Các vấn đề liên quan