C# 4.0 和 Word 2007 自动化

发布于 2024-10-21 11:48:38 字数 5680 浏览 1 评论 0原文

我正在创建一个应用程序,该应用程序从 Oracle 数据库获取数千个 Word 文档,需要将它们转换为 pdf 并将它们发送回数据库。我已经启动并运行了所有支持机制(数据库交互、多任务处理以及可插入的数据库和配置方法)。尽管有关于在服务器端使用办公自动化的所有警告,我的第一个方法是使用它(事实是我的客户要求使用它)。但我对 c# (.Net 4.0) 和 word 2007 之间的交互感到疯狂。我已经尝试过 SaveAs 和 ExportAsFixedFormat。两者都工作正常,但是当我尝试关闭该单词时...我收到一个错误(弹出窗口说该单词发现问题并将被关闭)。然后我尝试在退出应用程序之前包含此内容:

wordApplication.NormalTemplate.Saved = true;

但它仍然抛出错误。我无法在没有错误的情况下转换一百多个文档。您知道在不使用办公自动化的情况下实现这种转换的一些方法吗?或者另一方面,您知道如何通过办公自动化来无误地进行这种转换吗?任何帮助将不胜感激。

编辑: Otaku,这是我正在使用的代码示例(警告!提前测试代码)

 if (wordApplication == null)
        {
            try
            {
                wordApplication = (ApplicationClass)System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application") ??
                             new ApplicationClass();
            }
            catch (COMException)
            {
                Type type = Type.GetTypeFromProgID("Word.Application");
                wordApplication = (ApplicationClass)System.Activator.CreateInstance(type);
            }

        }


        wordApplication.DisplayAlerts = WdAlertLevel.wdAlertsNone;
        wordApplication.DisplayRecentFiles = false;
        wordApplication.Visible = false;
        wordApplication.ScreenUpdating = false;

        Document wordDocument = null;

        object paramSourceDocPath = Path.Combine(TempFolder, sourceFilename);
        var paramExportFilePath = Path.Combine(TempFolder, sourceFilename + ".pdf");
        var paramMissing = Type.Missing;

        const WdExportFormat paramExportFormat = WdExportFormat.wdExportFormatPDF;
        const bool paramOpenAfterExport = false;
        const WdExportOptimizeFor paramExportOptimizeFor = WdExportOptimizeFor.wdExportOptimizeForPrint;
        const WdExportRange paramExportRange = WdExportRange.wdExportAllDocument;
        const int paramStartPage = 0;
        const int paramEndPage = 0;
        const WdExportItem paramExportItem = WdExportItem.wdExportDocumentContent;
        const bool paramIncludeDocProps = true;
        const bool paramKeepIrm = true;
        const WdExportCreateBookmarks paramCreateBookmarks = WdExportCreateBookmarks.wdExportCreateWordBookmarks;
        const bool paramDocStructureTags = true;
        const bool paramBitmapMissingFonts = true;
        const bool paramUseIso190051 = false;

        try
        {
            // Open the source document.
            wordDocument = wordApplication.Documents.Open(
                ref paramSourceDocPath, ref paramMissing, ref paramMissing,
                ref paramMissing, ref paramMissing, ref paramMissing,
                ref paramMissing, ref paramMissing, ref paramMissing,
                ref paramMissing, ref paramMissing, ref paramMissing,
                ref paramMissing, ref paramMissing, ref paramMissing,
                ref paramMissing);

            // Export it in the specified format.
            if (wordDocument != null)
            {

                //DocumentSaveAs(wordDocument);

                Logger.Write("Open document" + sourceFilename, "info");
                wordDocument.ExportAsFixedFormat(paramExportFilePath,
                                                 paramExportFormat, paramOpenAfterExport,
                                                 paramExportOptimizeFor, paramExportRange, paramStartPage,
                                                 paramEndPage, paramExportItem, paramIncludeDocProps,
                                                 paramKeepIrm, paramCreateBookmarks, paramDocStructureTags,
                                                 paramBitmapMissingFonts, paramUseIso190051,
                                                 ref paramMissing);
            }
        }
        catch (Exception ex)
        {
            Logger.Write(ex.Message);
            throw;
        }
        catch
        {
            Logger.Write("Empty catch.");
            throw;
        }
        finally
        {
            try
            {

            object saveChanges = WdSaveOptions.wdDoNotSaveChanges;
            // Close and release the Document object.
            if (wordDocument != null)
            {

                wordDocument.Close(ref saveChanges, ref paramMissing,
                                   ref paramMissing);
                Thread.Sleep(2000);
                wordDocument = null;
            }

            // Quit Word and release the ApplicationClass object.

            foreach (Document document in wordApplication.Documents)
            {
                document.Close(saveChanges, paramMissing, paramMissing);
            }
            wordApplication.NormalTemplate.Saved = true;
            wordApplication.Quit(ref saveChanges, ref paramMissing,
                                 ref paramMissing);
            //Thread.Sleep(1000);
            wordApplication = null;


            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
            GC.WaitForPendingFinalizers();


            Logger.Write("Deleting word file " + sourceFilename, "info");
            File.Delete(paramSourceDocPath.ToString());
            Logger.Write("File deleted " + sourceFilename, "info");

            Logger.Write("Reading pdf data " + paramExportFilePath, "info");
            ret = File.ReadAllBytes(paramExportFilePath);
            Logger.Write("Data read " + sourceFilename + ".pdf", "info");
            File.Delete(paramExportFilePath);
            Logger.Write("Pdf file deleted " + paramExportFilePath, "info");
            }
            catch (Exception e)
            {
                Logger.Write(e,"info");
                throw;
            }

I am creating an application that gets thousands of word documents from an Oracle database and need to transform them into pdf and send them back to database. I already have all the support mechanism (database interaction, multitasking and a plugable approach to database and configuration) up and running. In spite of all warnings about using office automation in the server side my first approach was to use it (the truth is that my customer asked to use it). But I'm going mad with the interaction between c# (.Net 4.0) and word 2007. I already tried the SaveAs and the ExportAsFixedFormat. Both worked fine but when I try to close the word... I got an erro (pop up window saying that word found a problem and will be closed). Then I tried to include this before quitting the application:

wordApplication.NormalTemplate.Saved = true;

But it still throwing the errror. I'm unable to convert more than one hundred docs without an error. Do you know some way to achieve this conversion without using office automation? Or in the other hand, do you know how to do this conversion through office automation without errors? Any help will be very appreciated.

EDIT:
Otaku, here is an example of the code I am using (WARING! testing code ahead)

 if (wordApplication == null)
        {
            try
            {
                wordApplication = (ApplicationClass)System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application") ??
                             new ApplicationClass();
            }
            catch (COMException)
            {
                Type type = Type.GetTypeFromProgID("Word.Application");
                wordApplication = (ApplicationClass)System.Activator.CreateInstance(type);
            }

        }


        wordApplication.DisplayAlerts = WdAlertLevel.wdAlertsNone;
        wordApplication.DisplayRecentFiles = false;
        wordApplication.Visible = false;
        wordApplication.ScreenUpdating = false;

        Document wordDocument = null;

        object paramSourceDocPath = Path.Combine(TempFolder, sourceFilename);
        var paramExportFilePath = Path.Combine(TempFolder, sourceFilename + ".pdf");
        var paramMissing = Type.Missing;

        const WdExportFormat paramExportFormat = WdExportFormat.wdExportFormatPDF;
        const bool paramOpenAfterExport = false;
        const WdExportOptimizeFor paramExportOptimizeFor = WdExportOptimizeFor.wdExportOptimizeForPrint;
        const WdExportRange paramExportRange = WdExportRange.wdExportAllDocument;
        const int paramStartPage = 0;
        const int paramEndPage = 0;
        const WdExportItem paramExportItem = WdExportItem.wdExportDocumentContent;
        const bool paramIncludeDocProps = true;
        const bool paramKeepIrm = true;
        const WdExportCreateBookmarks paramCreateBookmarks = WdExportCreateBookmarks.wdExportCreateWordBookmarks;
        const bool paramDocStructureTags = true;
        const bool paramBitmapMissingFonts = true;
        const bool paramUseIso190051 = false;

        try
        {
            // Open the source document.
            wordDocument = wordApplication.Documents.Open(
                ref paramSourceDocPath, ref paramMissing, ref paramMissing,
                ref paramMissing, ref paramMissing, ref paramMissing,
                ref paramMissing, ref paramMissing, ref paramMissing,
                ref paramMissing, ref paramMissing, ref paramMissing,
                ref paramMissing, ref paramMissing, ref paramMissing,
                ref paramMissing);

            // Export it in the specified format.
            if (wordDocument != null)
            {

                //DocumentSaveAs(wordDocument);

                Logger.Write("Open document" + sourceFilename, "info");
                wordDocument.ExportAsFixedFormat(paramExportFilePath,
                                                 paramExportFormat, paramOpenAfterExport,
                                                 paramExportOptimizeFor, paramExportRange, paramStartPage,
                                                 paramEndPage, paramExportItem, paramIncludeDocProps,
                                                 paramKeepIrm, paramCreateBookmarks, paramDocStructureTags,
                                                 paramBitmapMissingFonts, paramUseIso190051,
                                                 ref paramMissing);
            }
        }
        catch (Exception ex)
        {
            Logger.Write(ex.Message);
            throw;
        }
        catch
        {
            Logger.Write("Empty catch.");
            throw;
        }
        finally
        {
            try
            {

            object saveChanges = WdSaveOptions.wdDoNotSaveChanges;
            // Close and release the Document object.
            if (wordDocument != null)
            {

                wordDocument.Close(ref saveChanges, ref paramMissing,
                                   ref paramMissing);
                Thread.Sleep(2000);
                wordDocument = null;
            }

            // Quit Word and release the ApplicationClass object.

            foreach (Document document in wordApplication.Documents)
            {
                document.Close(saveChanges, paramMissing, paramMissing);
            }
            wordApplication.NormalTemplate.Saved = true;
            wordApplication.Quit(ref saveChanges, ref paramMissing,
                                 ref paramMissing);
            //Thread.Sleep(1000);
            wordApplication = null;


            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
            GC.WaitForPendingFinalizers();


            Logger.Write("Deleting word file " + sourceFilename, "info");
            File.Delete(paramSourceDocPath.ToString());
            Logger.Write("File deleted " + sourceFilename, "info");

            Logger.Write("Reading pdf data " + paramExportFilePath, "info");
            ret = File.ReadAllBytes(paramExportFilePath);
            Logger.Write("Data read " + sourceFilename + ".pdf", "info");
            File.Delete(paramExportFilePath);
            Logger.Write("Pdf file deleted " + paramExportFilePath, "info");
            }
            catch (Exception e)
            {
                Logger.Write(e,"info");
                throw;
            }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

白日梦 2024-10-28 11:48:38

我们使用名为 Aspose 的商业产品来进行所有 Office 集成(因为它实际上不需要 Office,速度非常快,并且不是 Interop)。我不能 100% 确定是否支持您的具体场景,但他们的网站上有很多示例,如果您的项目支持购买几个许可证,这可以让您的生活变得更轻松。

We use a commercial product called Aspose for all our Office integrations (as it does not actually require Office, is very fast, and is not Interop). I am not 100% sure if your exact scenario would be supported, but they have many samples on their website and if your project supports buying the couple licenses this can make your life a lot easier.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文