以编程方式编辑Word Doc C#

时间:2016-03-12 00:26:35

标签: c# visual-studio-2010 ms-word .net-4.0 office-interop

C#,Visual Studio 2010,.NET 4.0

我正在尝试编辑单词doc模板并搜索特定字符串并将其替换为我的C#程序中的值。我尝试过使用Microsoft.Office.Interop.Word,如果在环境中安装了Office 2003或更高版本,事情就会很好用。问题是,我需要它处理的环境是使用Word 2000并且升级它不是一个选项,因为该PC上的某些其他程序需要2000.

所以我尝试在Notepad ++中打开模板文档,它打开很好,它有一堆奇怪的字母和东西,但我可以找到/替换我的值并保存。然后,当我打开保存的文档时,它看起来很棒。大!那我怎么用我的程序呢?我已经尝试过使用File类,我已经尝试过StreamWriter但是都将文件保存为垃圾,所以当我尝试用文字打开它们时,他们会问我使用的是什么编码,这似乎不起作用。< / p>

知道我需要使用什么编码?或者Notepad ++如何编辑文档并以正确的格式保存?

    //Using Microsoft Office Interop Word
        private void method0()
        {
            Microsoft.Office.Interop.Word._Document aDoc = null;
            object missing = System.Reflection.Missing.Value;
            Microsoft.Office.Interop.Word._Application wordApp = new Microsoft.Office.Interop.Word.Application();

            try
            {
                if (File.Exists("AIO2CertTemplate.doc"))
                {
                    DateTime today = DateTime.Now;

                    object fileName = System.Windows.Forms.Application.StartupPath + "\\AIO2CertTemplate.doc";
                    object saveFileName = textBoxSaveFilePath.Text;
                    object readOnly = false;
                    object isVisible = true;

                    wordApp.Visible = true;

                    aDoc = wordApp.Documents.Open(ref fileName, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref isVisible, ref missing, ref missing, ref missing, ref missing);

                    aDoc.Activate();

                    this.FindAndReplace(wordApp, "<Model>", textBoxModel.Text);
                    this.FindAndReplace(wordApp, "<Serial#>", textBoxSerial.Text);
                    this.FindAndReplace(wordApp, "<CalBy>", textBoxCalBy.Text);
                    this.FindAndReplace(wordApp, "<Cal Date>", today.ToShortDateString());
                    this.FindAndReplace(wordApp, "<InspectedBy>", textBoxInspBy.Text);
                    this.FindAndReplace(wordApp, "<Insp Date>", today.ToShortDateString());

                    aDoc.SaveAs(ref saveFileName, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
                    //wordApp.Quit();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                aDoc.Close();
                wordApp.Quit();
            }
        }

使用文件类

private void method1()
        {
            string templateFilePath = System.Windows.Forms.Application.StartupPath + "\\AIO2CertTemplate.doc";

            string text = File.ReadAllText(templateFilePath);
            text = text.Replace("<Model>", textBoxModel.Text);
            text = text.Replace("<Serial#>", textBoxSerial.Text);
            text = text.Replace("<CalBy>", textBoxCalBy.Text);
            text = text.Replace("<Cal Date>", DateTime.Now.ToShortDateString());
            text = text.Replace("<InspectedBy>", textBoxInspBy.Text);
            text = text.Replace("<Insp Date>", DateTime.Now.ToShortDateString());

            //System.Text.ASCIIEncoding enc = new ASCIIEncoding();
            //System.Text.Encoding.Unicode

            File.WriteAllText(textBoxSaveFilePath.Text, text, System.Text.Encoding.Default);
        }

使用StreamWriter

private void method2()
        {
            StreamWriter sw = new StreamWriter(textBoxSaveFilePath.Text);
            string templateFilePath = System.Windows.Forms.Application.StartupPath + "\\AIO2CertTemplate.doc";

            using (StreamReader sr = new StreamReader(templateFilePath))
            {
                string line;

                while ((line = sr.ReadLine()) != null)
                {
                    line = line.Replace("<Model>", textBoxModel.Text);
                    line = line.Replace("<Serial#>", textBoxSerial.Text);
                    line = line.Replace("<CalBy>", textBoxCalBy.Text);
                    line = line.Replace("<Cal Date>", DateTime.Now.ToShortDateString());
                    line = line.Replace("<InspectedBy>", textBoxInspBy.Text);
                    line = line.Replace("<Insp Date>", DateTime.Now.ToShortDateString());

                    sw.WriteLine(line);
                }
            }

            sw.Close();
        }

先谢谢!

编辑:这是我的查找和替换方法

private void FindAndReplace(Microsoft.Office.Interop.Word.Application doc, object findText, object replaceWithText)
{
    //options
    object matchCase = false;
    object matchWholeWord = true;
    object matchWildCards = false;
    object matchSoundsLike = false;
    object matchAllWordForms = false;
    object forward = true;
    object format = false;
    object matchKashida = false;
    object matchDiacritics = false;
    object matchAlefHamza = false;
    object matchControl = false;
    object read_only = false;
    object visible = true;
    object replace = 2;
    object wrap = 1;
    //execute find and replace
    doc.Selection.Find.Execute(ref findText, ref matchCase, ref matchWholeWord,
        ref matchWildCards, ref matchSoundsLike, ref matchAllWordForms, ref forward, ref wrap, ref format, ref replaceWithText, ref replace,
        ref matchKashida ,ref matchDiacritics, ref matchAlefHamza, ref matchControl);                
}

编辑#2: 我做了Cindy posted我需要为Word 2000创建一个自己的IA。我在C上创建了一个临时文件夹:通过命令提示符轻松导航。我复制了TlbImp.exe(在C:/ Program Files / Microsoft SDK /中找到)和安装了Windows 2000的PC上找到的MS Word OLB文件(C:/ Program Files / Microsoft Office / Office)。然后我打开了我的命令提示符(start-&gt; run-&gt; cmd.exe)。导航到我的临时文件夹cd C:\Temp,然后运行以下cmd TlbImp.exe MSWORD9.OLB /out: Microsoft.Office.Interop.Word.dll,它会在您的目录中创建一个dll。然后我删除了我的旧Interop引用并添加了这个新的dll。我不得不将我的命名空间更改为using MSOffice.Word;,然后更新命令,因为它们现在比新版本的dll采用更少的参数。以下是我更新的方法:

private void FindAndReplace(MSOffice.Word._Application WordApp, object findText, object replaceWithText)
        {
            object matchCase = true;
            object matchWholeWord = true;
            object matchWildCards = false;
            object matchSoundsLike = false;
            object matchAllWordForms = false;
            object forward = true;
            object format = false;
            object matchKashida = false;
            object matchDiacritics = false;
            object matchAlefHamza = false;
            object matchControl = false;
            object read_only = false;
            object visible = true;
            object replace = 2;
            object wrap = 1;

            WordApp.Selection.Find.Execute(ref findText, ref matchCase, ref matchWholeWord, ref matchWildCards, ref matchSoundsLike,
                ref matchAllWordForms, ref forward, ref wrap, ref format, ref replaceWithText, ref replace, ref matchKashida,
                ref matchDiacritics, ref matchAlefHamza, ref matchControl);
        }

        private void method0()
        {
            MSOffice.Word._Document aDoc = null;
            object missing = System.Reflection.Missing.Value;
            MSOffice.Word._Application wordApp = new MSOffice.Word.Application();

            try
            {
                if (File.Exists("AIO2CertTemplate.doc"))
                {
                    DateTime today = DateTime.Now;

                    object fileName = System.Windows.Forms.Application.StartupPath + "\\AIO2CertTemplate.doc";
                    object saveFileName = textBoxSaveFilePath.Text;
                    object readOnly = false;
                    object isVisible = true;

                    wordApp.Visible = true;

                    //aDoc = wordApp.Documents.Open(ref fileName, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref isVisible, ref missing, ref missing, ref missing, ref missing);
                    aDoc = wordApp.Documents.Open(ref fileName, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref isVisible);

                    aDoc.Activate();

                    this.FindAndReplace(wordApp, "<Model>", textBoxModel.Text);
                    this.FindAndReplace(wordApp, "<Serial#>", textBoxSerial.Text);
                    this.FindAndReplace(wordApp, "<CalBy>", textBoxCalBy.Text);
                    this.FindAndReplace(wordApp, "<Cal Date>", today.ToShortDateString());
                    this.FindAndReplace(wordApp, "<InspectedBy>", textBoxInspBy.Text);
                    this.FindAndReplace(wordApp, "<Insp Date>", today.ToShortDateString());

                    //aDoc.SaveAs(ref saveFileName, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
                    aDoc.SaveAs(ref saveFileName, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
                    //wordApp.Quit();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                aDoc.Close();
                wordApp.Quit();
            }
        }

它可以被清理一下,但这是我学到的基本信息,让这个东西起作用。

2 个答案:

答案 0 :(得分:1)

在Office 2000中使用“Interop”涉及的步骤多于后续版本。那是因为微软没有为Office 2000提供任何PIA。

(IA = Interop Assembly。这是COM类型库和.NET Framework之间的“转换”.PIA =主互操作程序集,是由类型库的“所有者”分发的IA的优化版本。 PIA安装在GAC中并且是特定于版本的.IAs不是特定于版本的,但可能在与COM库通信时遇到某些问题。)

因此,您需要创建一组IA以提供.NET与Office COM类型库(* .tlb)之间的通信服务。您的项目将引用这些项目,并且需要与项目一起分发。

Visual Studio的Windows SDK提供tlbimp.exe作为生成IA的命令行工具。这是基本语法:

tlbimp <type-library-file>

可以在MSDN文档中找到更多信息:https://msdn.microsoft.com/en-us/library/697w37zd(v=vs.110).aspx

另一种与版本无关的方法是使用后期绑定(也称为使用GetType()调用PInvoke.InvokeMember)。

答案 1 :(得分:0)

这实际上只是猜测。 你说,它是Word 2000,意思是很老了。那时使用的编码可能是ANSI(在C#中是#Enc; Encoding.Default&#39;)。 如果我没记错的话,File类将尝试保存在utf-8中。