以编程方式编辑 Word Doc C#
Editing Word Doc Programmatically C#
C#,Visual Studio2010,.NET 4.0
我正在尝试编辑一个 word 文档模板并搜索特定字符串并将它们替换为我的 C# 程序中的值。我试过使用 Microsoft.Office.Interop.Word,如果环境中安装了 Office 2003 或更高版本,一切都运行良好。问题是,我需要它工作的环境是使用 Word 2000 并且升级它不是一个选项,因为该 PC 上的一些其他程序需要 2000。
所以我尝试在 Notepad++ 中打开模板文档,它打开得很好,它有一堆奇怪的字母和东西,但我可以 find/replace 我的值并保存。然后当我打开保存的文档时,它看起来很棒。伟大的!那么我将如何使用我的程序执行此操作?我试过使用 File class 并且试过 StreamWriter 但是两者都将文件保存为垃圾所以当我尝试用 word 打开它们时他们问我正在使用什么编码,但似乎没有上班。
知道我需要使用什么编码吗?或者 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();
}
}
使用文件Class
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:
我做了 我需要为 Word 2000 创建一个我自己的 IA。我在我的 C: 上创建了一个临时文件夹,以便通过命令提示符轻松导航。我复制了 TlbImp.exe(在 C:/Program Files/Microsoft SDK/ 中找到)和在安装了 Windows 2000 的 PC 上找到的 MS Word OLB 文件(C:/Program Files/Microsoft Office/Office)。然后我打开我的命令提示符 (start->运行->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();
}
}
它可以稍微清理一下,但这是我学到的让这个东西正常工作的基本信息。
在 Office 2000 中使用 "Interop" 比在更高版本中涉及更多步骤。那是因为 Microsoft 没有为 Office 2000 提供任何 PIA。
(IA = Interop Assembly。这是 COM 类型库和 .NET Framework 之间的 "translates"。PIA = Primary interop assembly 并且是由 "owner" 的类型库。PIA 安装在 GAC 中并且是特定于版本的。IA 不是特定于版本的,但可能在与 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().InvokeMember 的 PInvoke)。
C#,Visual Studio2010,.NET 4.0
我正在尝试编辑一个 word 文档模板并搜索特定字符串并将它们替换为我的 C# 程序中的值。我试过使用 Microsoft.Office.Interop.Word,如果环境中安装了 Office 2003 或更高版本,一切都运行良好。问题是,我需要它工作的环境是使用 Word 2000 并且升级它不是一个选项,因为该 PC 上的一些其他程序需要 2000。
所以我尝试在 Notepad++ 中打开模板文档,它打开得很好,它有一堆奇怪的字母和东西,但我可以 find/replace 我的值并保存。然后当我打开保存的文档时,它看起来很棒。伟大的!那么我将如何使用我的程序执行此操作?我试过使用 File class 并且试过 StreamWriter 但是两者都将文件保存为垃圾所以当我尝试用 word 打开它们时他们问我正在使用什么编码,但似乎没有上班。
知道我需要使用什么编码吗?或者 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();
}
}
使用文件Class
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:
我做了 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();
}
}
它可以稍微清理一下,但这是我学到的让这个东西正常工作的基本信息。
在 Office 2000 中使用 "Interop" 比在更高版本中涉及更多步骤。那是因为 Microsoft 没有为 Office 2000 提供任何 PIA。
(IA = Interop Assembly。这是 COM 类型库和 .NET Framework 之间的 "translates"。PIA = Primary interop assembly 并且是由 "owner" 的类型库。PIA 安装在 GAC 中并且是特定于版本的。IA 不是特定于版本的,但可能在与 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().InvokeMember 的 PInvoke)。