加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何将表插入Word文档代替文本标记?

发布时间:2020-12-15 18:36:22 所属栏目:百科 来源:网络整理
导读:我有DateTable.需要在teplate文档中插入它而不是某些字符集. 我可以用这种方式替换文本到文本(很多missingObj以避免错误): using Word = Microsoft.Office.Interop.Word; Word._Application application; Word._Document document; Object missingObj = Sys
我有DateTable.需要在teplate文档中插入它而不是某些字符集.

我可以用这种方式替换文本到文本(很多missingObj以避免错误):

using Word = Microsoft.Office.Interop.Word;

    Word._Application application;
    Word._Document document;
    Object missingObj = System.Reflection.Missing.Value;
    Object trueObj = true;
    Object falSEObj = false;

    private void create_button1_Click(object sender,EventArgs e) {
            application = new Word.Application();
            Object templatePathObj;
            templatePathObj = "template.dot";  

            try {
                document = application.Documents.Add(ref  templatePathObj,ref missingObj,ref missingObj);
            }
            catch (Exception error) {
                document.Close(ref falSEObj,ref  missingObj,ref missingObj);
                application.Quit(ref missingObj,ref missingObj);
                document = null;
                application = null;
                throw error;
            }

            object strToFindObj = "%%mark%%";
            object replaceStrObj = "text to replace";
            Word.Range wordRange;
            object replaceTypeObj;
            replaceTypeObj = Word.WdReplace.wdReplaceAll;
            for (int i = 1; i <= document.Sections.Count; i++) {
                wordRange = document.Sections[i].Range;
                Word.Find wordFindObj = wordRange.Find;
                object[] wordFindParameters = new object[15] { strToFindObj,missingObj,replaceStrObj,replaceTypeObj,missingObj };
                wordFindObj.GetType().InvokeMember("Execute",BindingFlags.InvokeMethod,null,wordFindObj,wordFindParameters);
        }
        application.Visible = true;
    }

我必须改变所以这个代码将采用DataTable而不是strToFindObj?

在这个例子中,我替换Range中的东西,什么是文档的碎片,包括表格,格式等.

解决方法

lots of missingObj to avoid the bugs

目标.Net 4.0或更高版本支持COM调用的命名和可选参数,因此您不需要包含所有ref missingObj.请参阅此MSDN文章:Named and Optional Arguments – 此功能极大地方便了对COM接口(如Microsoft Office Automation API)的调用.

What do I have to change so I can search using a DataTable instead
of string variable strToFindObj?

您必须遍历DataTables Row和Cell替换Word文档中的DataTable单元格,例如:

foreach(var dr in dt.Rows)
{
  foreach (var cell in dr.ItemArray)
  {
    string strToFind = cell.ToString();
    string replaceStr = "replace old value";
    ReplaceTextInWord(@"C:Temptemplate.docx",strToFind,replaceStr);
  }
}

如果您发现太难使用DataTable并且想要一个更容易的列表(如字典):

var listOfTextToReplace = new Dictionary<string,string>();
listOfTextToReplace.Add("%%mark%%","text to replace");
foreach(var item in listOfTextToReplace )
{
    string strToFind = item.Key;
    string replaceStr = item.Value;
    ReplaceTextInWord(@"C:Temptemplate.docx",replaceStr);
}

这是ReplaceTextInWord方法:

using Word = Microsoft.Office.Interop.Word;
Word._Application application;
Word._Document document;
Object missingObj = System.Reflection.Missing.Value;
Object trueObj = true;
Object falSEObj = false;

private void create_button1_Click(object sender,EventArgs e) {
   //ReplaceTextInWord("template.dot","find me","Found"); <-- Are you sure you want to replace in a Template?
   ReplaceTextInWord(@"C:Temptemplate.docx","%%mark%%","text to replace");  //I think you want a .DOC or DOCX file
}

private void ReplaceTextInWord(string wordDocFilePath,string strToFind,string replaceStr) {
    application = new Word.Application();
    try {
        //document = application.Documents.Add(ref templatePathObj,ref missingObj); 
        document = application.Documents.Open(wordDocFilePath);  //You need to open Word Documents,not add them,as per https://msdn.microsoft.com/en-us/library/tcyt0y1f.aspx
    }
    catch (Exception error) {
        document.Close(ref falSEObj,ref missingObj);
        application.Quit(ref missingObj,ref missingObj);
        document = null;
        application = null;
        throw error;
    }

    for (int i = 1; i <= document.Sections.Count; i++) {
    Word.Range wordRange = document.Sections[i].Range;
    Word.Find findObject = wordRange.Find;
    findObject.ClearFormatting();
    findObject.Text = strToFind;
    findObject.Replacement.ClearFormatting();
    findObject.Replacement.Text = replaceStr;

    object replaceAll = Word.WdReplace.wdReplaceAll;
    findObject.Execute(ref missing,ref missing,ref replaceAll,ref missing);
    }
    application.Visible = true;
}

参考MSDN:How to: Programmatically Search for and Replace Text in Documents

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读