使用c#使用Open xml替换单词表中的令牌

问题描述 投票:0回答:1

我有一个要求,我要根据计数将单词表克隆到多个表中并插入到Word文档中。如果我有5条记录,则应使用现有表克隆添加5个表并替换表内的令牌。它正在添加5个表,但是它将用最后一条记录替换所有五个表的内容,因此所有五个表都具有与最后一行相同的数据。

//Main code
string tableInnerText = tblMain.InnerText;
List<string> fieldsList = GetFieldList(tableInnerText, repeatedTableListName);

var parentParagraph = printBookmarkStart.Parent;
tbl[0].Remove();
for (int rowIndex = 0; rowIndex < dt.Rows.Count; rowIndex++)
{
  if (pageBreak.ToUpper() == "YES" && rowIndex > 0)
  {
    _wordDoc.MainDocumentPart.Document.Body.InsertAfter(new Paragraph(new Run(new Break() { Type = BreakValues.Page })), parentParagraph);
  }

  tblMainTmp = (Table)tblMain.Clone();
  _wordDoc.MainDocumentPart.Document.Body.InsertAfter<Table>(tblMainTmp, parentParagraph);
  _wordDoc.MainDocumentPart.Document.Save();
  UpdateRepeatedTable(dt.Rows[rowIndex], dt, rowIndex, fieldsList, repeatedTableListName);
} 

[...]

private void UpdateRepeatedTable(DataRow dr, DataTable dt, int dataRowIndex, List<string> tableColumnsList, string repeatedTableListName)
{
    try
    {
        DataTable dtFunction = GetFunctionDataTable(tableColumnsList, repeatedTableListName);

        for (int j = 0; j < tableColumnsList.Count; j++)
        {
            string dtColumnName = ParseRelatedListFieldName(tableColumnsList[j], repeatedTableListName, true);
            string dtColumnValue = dr[dtColumnName].ToString();
            string formatValue = string.Empty;

            string replaceValue = dtColumnValue;
            //TODO: Check if fields a function field
            DataRow[] findRow = dtFunction.Select(string.Format("FieldName='{0}'", tableColumnsList[j]));
            bool bIsCheckBoxField = false;
            if (findRow.Length > 0)
            {
                bIsCheckBoxField = (findRow[0]["FunctionName"].ToString().ToUpper() == "CHECKBOX" ? true : false);
                formatValue = findRow[0]["Format"].ToString();
                replaceValue = GetFunctionValue(dt, 0, findRow[0], ""/*, null*/);
            }

            _clsLog.WriteMessage("Replacing " + tableColumnsList[j] + " with " + replaceValue, ClsLog.LogType.Log);

            SearchAndReplacer.SearchAndReplace(_wordDoc, tableColumnsList[j], replaceValue, true);              

            if (bIsCheckBoxField == true)
            {
                ProcessStandardFieldCheckBox(/*wordApp,*/ dtColumnValue, formatValue);
            }
        }
    }
    catch (Exception ex)
    {
        _clsLog.WriteMessage(ex);
    }
}

http://www.ericwhite.com/blog/search-and-replace-text-in-an-open-xml-wordprocessingml-document/

c# openxml openxml-sdk
1个回答
0
投票

我能够使用open-xml-powertools中的DocumentAssembler(http://www.ericwhite.com/blog/documentassembler-developer-center/)解决此问题,这是Eric White建议的。

DocumentAssembler提供了处理文档的选项,以重复内容,表格,匹配条件。

© www.soinside.com 2019 - 2024. All rights reserved.