문제

Word 2007은 문서를 .docx 형식으로 저장합니다. 이는 실제로 문서가 포함된 xml 파일을 포함하여 많은 내용이 포함된 zip 파일입니다.

.docx 파일을 가져와 내 asp.net 웹 앱의 폴더에 놓고 코드에서 .docx 파일을 열고 문서의 (xml 부분)을 웹 페이지로 렌더링할 수 있기를 원합니다.

이에 대해 더 많은 정보를 얻기 위해 웹을 검색해 봤지만 지금까지 많은 정보를 찾지 못했습니다.내 질문은 다음과 같습니다

  1. (a) XSLT를 사용하여 XML을 HTML로 변환하시겠습니까, 아니면 (b) .net의 xml 조작 라이브러리(예: 3.5의 XDocument 및 XElement)를 사용하여 HTML로 변환하시겠습니까, 아니면 (c) 기타를 사용하시겠습니까?
  2. 시작점으로 사용할 수 있는 이 작업을 수행한 오픈 소스 라이브러리/프로젝트를 알고 있습니까?

감사해요!

도움이 되었습니까?

해결책

이 시도 우편?나는 모르지만 당신이 찾고 있는 것일 수도 있습니다.

다른 팁

나는 썼다 mammoth.js, docx 파일을 HTML로 변환하는 JavaScript 라이브러리입니다..NET에서 서버측 렌더링을 수행하려는 경우 Mammoth의 .NET 버전도 있습니다. NuGet에서 사용 가능.

Mammoth는 의미 정보를 살펴봄으로써 깔끔한 HTML을 생성하려고 합니다. 예를 들어 Word의 단락 스타일 매핑(예: Heading 1)을 HTML/CSS의 적절한 태그 및 스타일(예: <h1>).정확한 시각적 사본을 생성하는 것을 원한다면 Mammoth는 아마도 당신에게 적합하지 않을 것입니다.이미 잘 구조화된 항목이 있고 이를 깔끔한 HTML로 변환하려는 경우 Mammoth가 그 트릭을 수행할 수 있습니다.

Word 2007에는 HTML로 변환하는 데 사용할 수 있는 API가 있습니다.이에 대해 이야기한 포스팅이 있습니다 http://msdn.microsoft.com/en-us/magazine/cc163526.aspx.API에 대한 문서를 찾을 수 있지만 API에 HTML로 변환 기능이 있다는 것을 기억합니다.

이 코드는 변환하는 데 도움이 됩니다 .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\t@\/\_\(\)]/","",$striped_content);

    echo nl2br($striped_content); 
}

인터롭을 사용하고 있습니다.다소 문제가 있지만 대부분의 경우 잘 작동합니다.

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

이것은 HTML로 변환된 문서의 경로 목록을 반환합니다.

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;
    }

그리고 이것은 문서를 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();
            }
        }
    }

말 죽이는 것도 재미없지만, 거기에 매달리고 다른 사람을 막게 놔둘 수는 없겠죠?

웹/html에서 나는 html을 iframe으로 렌더링합니다.

도움말 문서 목록이 포함된 드롭다운이 있습니다.값은 HTML 버전의 경로이고 텍스트는 문서의 이름입니다.

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();

    }

선택한 인덱스가 변경되면 프레임으로 다시 생성됩니다.

    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";
        }
    }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top