我有2010年的信息表格。设计成学生信息。我希望使用带有指定报表模板的OpenXMl生成作为word文档的报表。我设计的表格如此之远,
但无法理解如何使用c#将变量值映射到word模板内容控件。Herewith1]网络OpenXMl的一个很好的例子。但它使用的是自定义Xml部件,用于将数据从xml文件转储到word模板。
如何用模板内容控件映射字符串变量?这有什么参考链接吗?
发布于 2011-09-13 13:58:32
我不得不做一些非常类似的事情,最后我使用了自定义的"PlaceHolder“字段,而不是单词字段(它们确实有各种限制,比如-页眉、页脚和身体--它们都使用不同的对象)。
在我的单词模板中,我标记了这样一个PlaceHolder -- ##MyPlaceHolderName!#。然后,我解析了单词模板的文本,以使用RegEx查找所有的RegEx,并将它们替换为InfoPath表单的实际值。
这种解决方案的唯一缺点是,您的PlaceHolders和InfoPath字段需要同名,否则您将无法进行任何匹配。
考虑一下这种方法:
private void FillDocument(Stream documentStream, string xmlFields)
{
var doc = new XmlDocument();
doc.LoadXml(xmlFields);
var props = doc.SelectSingleNode("properties");
if (props == null) throw new Exception("No properties found.");
//transform the xml properties to dictionary for easier replacement
var fields = props.ChildNodes.Cast<XmlNode>().ToDictionary
(node => string.Format("##{0}!#", node.Name), node => node.InnerText);
using (var document = WordprocessingDocument.Open(documentStream, true))
{
var main = document.MainDocumentPart;
//replace the fields in the main document
main.Document.InnerXml = ReplaceFields(main.Document.InnerXml, fields);
//replace the fields in the headers
foreach (var headerPart in main.HeaderParts)
headerPart.Header.InnerXml = ReplaceFields(headerPart.Header.InnerXml, fields);
//replace the fields in the footers
foreach (var footerPart in main.FooterParts)
footerPart.Footer.InnerXml = ReplaceFields(footerPart.Footer.InnerXml, fields);
main.Document.Save();
}
}
private string ReplaceFields(string xmlPart, Dictionary<string, string> fields)
{
//searches the xml for the declared fields
var fieldRegex = new Regex("##[^#]*!#");
var matches = fieldRegex.Matches(xmlPart);
foreach (Match match in matches)
{
//the fields are within tags (InnerText) so remove all other xml stuff
var innerRegex = new Regex("<[^>]*>");
string fieldName = innerRegex.Replace(match.Groups[0].Value, "");
//replace the actual value of the field
if(fields.ContainsKey(fieldName))
xmlPart = xmlPart.Replace(match.Groups[0].Value, fields[fieldName]);
}
return xmlPart;
}你可以这样使用它:
//open the file from as stream (in this example, the file is opened from SP
using (var stream = templateFile.OpenBinaryStream())
{
//iterate the properties you need and add them in this format
var xmlProperties = "<properties><MyPlaceHolderName>MyPlaceHolderValue</MyPlaceHolderName></properties>";
//fill out the fields
FillDocument(stream, xmlProperties);
}我知道Xml替换和xmlProperties是比较疯狂的,但由于我的需求( WebService从InfoPath调用方法),我不得不这样实现它。如果你需要进一步的帮助,请告诉我。
https://stackoverflow.com/questions/7358861
复制相似问题