我正在考虑一个.docx文档生成器。它基本上用作(它是一个C#控制台应用程序):
DocxGenerator.exe ATemplate.docx varsDefinations.txt
ATemplate.docx将提供一些要填充的基本模板。varsDefinations.txt将提供这些变量来填充字段。
然而,我根本不知道如何实现这一点。我一直在搜索Open和其他文档。目前的障碍是我在这种情况下应该使用什么领域。
例如,ATemplate.docx可能如下所示:
亲爱的{Field1},
我们很高兴地告诉你{Field2}。
你好,{Field3}
在varsDefinations.txt里,我想这样做:
Field1 =“回答我问题的可爱的人”;Field2 =“你是有史以来最好的”;Field3 =“佩森”;
有人做过这样的事吗?(我相信这是肯定的!因为我收到这么多“对不起”的信。)
总括而言,我的问题是:
提前谢谢你。
编辑1?
这个会有帮助的。这正是我想要的。
发布于 2014-01-14 00:56:19
嗨,我建议你在文本文件中的每一个信息之间留一个分隔符。
我想您的文本文件( varsDefinations.txt)是这样的。注意,我把"-“作为分隔符保留在行之间。
varsDefinations.txt看起来是这样的:
Lovely people who answer my question -
that you are the best ever -
Payson下面是生成word文档作为指定目标的代码。这里我正在处理.doc文件。您可以用.docx替换它。
这是根据您的要求编写的代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Data.OleDb;
namespace WordFileGeneratorFromTextFileConsoleApp
{
class Program
{
static void Main(string[] args)
{
try
{
string textfileName = "varsDefinations.txt";
string wordfileName = "ATemplate.doc";
string fileNameWithPath = @"C:\Quotations\" + wordfileName;
CustomMessage aMesssage = new CustomMessage();
//Reading from text file
using (FileStream fs =
new FileStream(@"C:\Quotations\" + textfileName,FileMode.OpenOrCreate, FileAccess.Read))
{
StreamReader sr = new StreamReader(fs);
string temp = sr.ReadToEnd();
string[] temparr = temp.Split('-');
for (int i = 0; i < temparr.Length;i++ )
{
string s = temparr[i];
if (s.Contains('\r'))
{
s = s.Replace('\r', ' ');
}
if (s.Contains('\n'))
{
s = s.Replace('\n', ' ');
}
temparr[i] = s;
}
if (temparr != null)
{
aMesssage.HeaderMessage = temparr[0];
aMesssage.MainMessage = temparr[1];
aMesssage.MessageSender = temparr[2];
}
sr.Close();
}
//Writing to word document
using (FileStream fs = new FileStream(fileNameWithPath, FileMode.OpenOrCreate, FileAccess.Write))
{
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine(aMesssage.HeaderMessage);
sw.WriteLine(aMesssage.MainMessage);
sw.WriteLine(aMesssage.MessageSender);
sw.Close();
}
//Opening Word Document
System.Diagnostics.Process.Start(fileNameWithPath);
}
catch (IOException ex)
{
Console.WriteLine(ex.Message.ToString());
}
catch (Exception ex2)
{
Console.WriteLine(ex2.Message.ToString());
}
}
}
class CustomMessage
{
public string HeaderMessage { get; set; }
public string MainMessage { get; set; }
public string MessageSender { get; set; }
}
}发布于 2014-01-14 07:48:40
有几件事要考虑。
首先,检查是否希望非IT人员从Microsoft中创建模板。
第二,您需要多次出现(一个循环)吗?
如果要由IT人员创建模板,可以使用以下方法:
如果模板是由非IT人员创建的,则方法变得更加复杂:
添加循环时,需要确保手动处理XML以避免XML片段被复制是不平衡的,或者创建平衡XML的算法,以确保重复元素一起形成有效的XML。
关于您的问题:我们已经开发了类似的软件,也许您可以使用我们使用的命名方法,比如$F{x}。该手册位于http://www.invantive.com/en/doc/invantive-composition/Invantive.Producer.Composition.Word.en.pdf和语法的第1.6节和进一步。
https://stackoverflow.com/questions/21102850
复制相似问题