//先复制模板出来
string sourceFilePath = Server.MapPath("/Resource/dowload/TestPaperByA4.docx");
string destinationFilePath = Server.MapPath("/temp/" + key); //目标
System.IO.File.Copy(sourceFilePath, destinationFilePath, true)
DocX doc = DocX.Load(destinationFilePath);
var paras = doc.Paragraphs;
Paragraph _XWPFParagraph = paras[i];
Regex regex = new Regex(@"\${(.*?)}"); //匹配两个字母间的数字串
var match = regex.Match(_XWPFParagraph.Text);
if (match.Groups.Count > 1)
{
string innerText0 = match.Groups[0].Value;
string innerText = match.Groups[1].Value;//占位符里面的值
}
Paragraph gp = doc.InsertParagraph();
gp.InsertText("");//段落插入值
Tools.HtmlToText2(ref doc, ref paragraph, content_End);
//content_End该值转换为html
HtmlDocument htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(content_End.Trim());
HtmlNode htmlNode = htmlDoc.DocumentNode;
foreach (HtmlNode node in htmlNode.ChildNodes)//做table表
{
if (node.Name.Equals("table") && node.GetAttributeValue("border", string.Empty).Equals("1"))
{
int z = 0;
foreach (var item in node.ChildNodes)//找最大的列数
{
if (z < item.ChildNodes.Count)
{
z = item.ChildNodes.Count;
}
}
Novacode.Table table = paragraph.InsertTableAfterSelf(node.ChildNodes.Count, z);
table.Alignment = Novacode.Alignment.center;
Novacode.Border bd = new Novacode.Border();
bd.Size = Novacode.BorderSize.two;
table.SetBorder(Novacode.TableBorderType.Bottom, bd);
table.SetBorder(Novacode.TableBorderType.InsideH, bd);
table.SetBorder(Novacode.TableBorderType.InsideV, bd);
table.SetBorder(Novacode.TableBorderType.Left, bd);
table.SetBorder(Novacode.TableBorderType.Right, bd);
table.SetBorder(Novacode.TableBorderType.Top, bd);
for (int i = 0; i < node.ChildNodes.Count; i++)
{
//string tr = node.ChildNodes[i].InnerText;
for (int j = 0; j < node.ChildNodes[i].ChildNodes.Count; j++)
{
string td = node.ChildNodes[i].ChildNodes[j].InnerText;
string tded = td.Replace(" ", " ");
if (j == 0)
{
// table.Rows[i].Cells[j].Width = tded.Length * 14;
}
else {
table.Rows[i].Cells[j].Width = 600 / z - 15;//这个根据需求设置每个td的width
}
table.Rows[i].Cells[j].Width = 600 / z - 15;
table.Rows[i].Cells[j].Paragraphs[0].Append(tded);
}
}
}