Сохранение нескольких документов Word в виде HTML через Office API - PullRequest
5 голосов
/ 12 сентября 2010

У меня есть большое количество документов Word, которые мне нужно проанализировать. Поскольку все они были созданы из одного шаблона, я думаю, что наилучшим подходом было бы сохранить их как файлы HTML и проанализировать сам HTML.

Хотя сохранить отдельный документ Word в формате HTML довольно просто, я не нашел способа выполнить массовую процедуру изнутри Word. Поэтому я пытаюсь найти способ использовать Microsoft Office / Word API для достижения этой цели.

Как использовать Word API для сохранения многих документов Word в формате HTML?

Заранее спасибо.

ОБНОВЛЕНИЕ: Еще несколько деталей ...

Некоторые документы имеют продление .doc, другие - .docx. Я надеюсь, что это не проблема, но если это так, мне просто нужно преобразовать их все в .docx, надеюсь, с помощью API или DocX .

Говоря о DocX, я увидел в блоге автора , что можно сохранить файл .docx в формате HTML со следующим кодом:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Word = Microsoft.Office.Interop.Word;
using Microsoft.Office.Interop.Word;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            // Convert Input.docx into Output.doc
            Convert(@"C:\users\cathal\Desktop\Input.docx", @"c:\users\cathal\Desktop\Output.doc", WdSaveFormat.wdFormatDocument);

            /*
             * Convert Input.docx into Output.pdf
             * Please note: You must have the Microsoft Office 2007 Add-in: Microsoft Save as PDF or XPS installed
             * http://www.microsoft.com/downloads/details.aspx?FamilyId=4D951911-3E7E-4AE6-B059-A2E79ED87041&displaylang=en
             */
            Convert(@"c:\users\cathal\Desktop\Input.docx", @"c:\users\cathal\Desktop\Output.pdf", WdSaveFormat.wdFormatPDF);

            // Convert Input.docx into Output.html
            Convert(@"c:\users\cathal\Desktop\Input.docx", @"c:\users\cathal\Desktop\Output.html", WdSaveFormat.wdFormatHTML);
        }

        // Convert a Word 2008 .docx to Word 2003 .doc
        public static void Convert(string input, string output, WdSaveFormat format)
        {
            // Create an instance of Word.exe
            Word._Application oWord = new Word.Application();

            // Make this instance of word invisible (Can still see it in the taskmgr).
            oWord.Visible = false;

            // Interop requires objects.
            object oMissing = System.Reflection.Missing.Value;
            object isVisible = true;
            object readOnly = false;
            object oInput = input;
            object oOutput = output;
            object oFormat = format;

            // Load a document into our instance of word.exe
            Word._Document oDoc = oWord.Documents.Open(ref oInput, ref oMissing, ref readOnly, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref isVisible, ref oMissing, ref oMissing, ref oMissing, ref oMissing);

            // Make this document the active document.
            oDoc.Activate();

            // Save this document in Word 2003 format.
            oDoc.SaveAs(ref oOutput, ref oFormat, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);

            // Always close Word.exe.
            oWord.Quit(ref oMissing, ref oMissing, ref oMissing);
        }
    }
}

Это лучший способ сделать это?

1 Ответ

4 голосов
/ 12 сентября 2010

Код, который вы разместили выше, должен выполнить эту работу за вас. Также насколько я знаю Document.SaveAs Api может конвертировать любой документ (docx, doc, rtf), который он может открыть в слове, в HTML (или любой другой формат)

также вместо создания экземпляра текстового приложения для каждого файла передайте строку [] имен в конвертируемый API и утилизируйте экземпляр документа только после того, как вы закончили с сохранением как

...