如何用c#填充一个可填充的word 2010文档
本文关键字:填充 一个 word 2010文档 何用 | 更新日期: 2023-09-27 18:29:14
如何创建现有MS Word 2010模板的实例(该模板只有1个文本框),获取可填充字段并在其中插入字符串?
所有这些在c#中,到目前为止我甚至无法打开.docx文档。
它不是免费的,但我已经用Syncfusion(在WinRT上)做到了这一点。您可以设置书签,然后在c#中导航到该书签并替换其内容(字符串、图像、表格等)。
http://www.syncfusion.com/
docu:http://help.syncfusion.com/winrt(DocIO是您正在搜索的内容)
他们有一个免费试用版,但也许你可以免费找到类似的东西(替换书签,如果你不能得到可填充的)(我没有,但只搜索了WinRT)
我能够用这些库做到这一点:
using Word = Microsoft.Office.Interop.Word;
using Microsoft.Office.Interop.Word;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using System.IO;
using Vladimir.Classes_Auxiliares;
这些字段:
public object Template;
public Object oFalse = false;
public Object oTrue = true;
public Object oMissing = System.Reflection.Missing.Value;
以及这些方法。第一个是打开Word应用程序(Visible=false),并根据保存的模板创建一个新文档。
public virtual Word.Document CriarDocumento(ETipoDeDocumento tipoDeDocumento, Word.Document doc, Word.Application word)
{
Template = tipoDeDocumento.ToString() + ".dotm";
doc = word.Documents.Add(Template, ref oMissing, ref oMissing, ref oMissing);
return doc;
}
下一个方法将查找内容或单词与Dictionary键匹配的文本和对象,用我想要的Dictionary表示的值填充活动文档,其中键与模板中的字符串相同,值是我想要传递给新文档的新值。
public virtual void PreencherDocumentoPorObjetoETexto(Dictionary<string, string> listaDeParametros, Word.Document doc)
{
foreach (Shape shape in doc.Shapes)
{
foreach (string key in listaDeParametros.Keys)
{
if (shape.TextFrame.TextRange.Text.Contains(key))
shape.TextFrame.TextRange.Text = listaDeParametros[key];
}
}
foreach (string key in listaDeParametros.Keys)
{
Word.Find findObject = doc.Application.Selection.Find;
findObject.ClearFormatting();
findObject.Text = key;
findObject.Replacement.ClearFormatting();
findObject.Replacement.Text = listaDeParametros[key];
object replaceAll = Word.WdReplace.wdReplaceAll;
findObject.Execute(ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref replaceAll, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
}
}
此方法最终将在打开打印对话框的情况下显示处于打印预览状态的Word应用程序。只有打印或取消选项。
public virtual void ImprimirDocumento(Word.Application word)
{
word.PrintPreview = true;
word.Visible = true;
Word.Dialog wordPrintDialog = word.Application.Dialogs[Word.WdWordDialog.wdDialogFilePrint];
wordPrintDialog.Show(ref oMissing);
}
每次使用这些方法打开文档时都应调用此方法,它将关闭文档和Word应用程序。
public virtual void FecharDocumento(Word.Document doc, Word.Application word)
{
System.Threading.Thread.Sleep(1000);
doc.Close(oFalse, oMissing, oMissing);
word.Quit(oFalse, oMissing, oMissing);
Marshal.FinalReleaseComObject(doc);
Marshal.FinalReleaseComObject(word);
}
如果您没有使用上面的方法完成Word应用程序,我建议您调用任务管理器并手动完成实例。