NovaCode DocX无法替换我的单词模板中的正确项目

时间:2016-05-14 17:46:36

标签: c# ms-word novacode-docx

我创建了一个使用DocX库生成doc文件的通用函数,但它不适用于我的doc模板中的所有项目。

它只替换了第一个项目,并在其他项目中生成相同的txt。我的doc参数设置如下:el0,el1,el3 .... el36

public void GenerateFile (string template, List<string> data)
{
    try { 
        //if (File.Exists(template))
        //{
        DocX dDocument;

        dDocument = DocX.Load(template);

        for (int i = 1; i < data.Count(); i++)
        {
            var item = data[i];

            if (item == null)
            {
                item = " ";
            }

            var el = "el" + i;
            dDocument.ReplaceText(el.ToString(), item);
        }

        string time = DateTime.Now.Year.ToString() + "" + DateTime.Now.Month.ToString() + "" + DateTime.Now.Day.ToString() + "" + DateTime.Now.Hour.ToString() + "" + DateTime.Now.Minute.ToString() + "" + DateTime.Now.Second.ToString() + "" + DateTime.Now.Millisecond.ToString();

        var path = HttpContext.Current.Server.MapPath("~/temp/" + Path.GetFileNameWithoutExtension(template) + "_" + time + ".docx");

        dDocument.SaveAs(path);
        downloadFile(path);
        //}
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

1 个答案:

答案 0 :(得分:0)

我已经更改了条目的概念,我使用了带键的字典,值

public void GenerateFile(string template, Dictionary<string, string> data)
    {
        try {
            DocX dDocument;

            dDocument = DocX.Load(template);


            foreach (var item in data)
            {
                dDocument.ReplaceText("[["+item.Key+"]]", item.Value);

            }

            var path = HttpContext.Current.Server.MapPath("~/temp/" + Path.GetFileNameWithoutExtension(template) + "_" + DateTime.Now.ToString("yyyyMMddHHmmssFFF") + ".doc");
            dDocument.SaveAs(path);
            downloadFile(path);
        }
        catch (Exception ex)
        {
            throw ex;
        }

        }