spire读入一个文档的内容复制到另一个文档的最后,保留所有原来格式,如果格式一样,应和目标文档的样式合并
一种是如下方法
Document destDoc = new Document();
destDoc.LoadFromFile("目标文档.docx");// 将源文档内容插入到目标文档末尾destDoc.InsertTextFromFile("源文档.docx", FileFormat.Docx);
destDoc.SaveToFile("结果文档.docx", FileFormat.Docx);这种方法格式是都保留了,但是没加进来一个文件,相同格式的样式会给你新建一个,直接炸你的样式表,而且后面文件的前几行样式会垮掉,我这直接标题1变成标题2。
一种是通过挨个Section复制:
foreach (DocumentObject obj in srcSection.Body.ChildObjects)
{
if (obj == null) continue;
newSection.Body.ChildObjects.Add(obj.Clone());
}
这种好像样式能通过你手动整理保持,样式表不会爆,但是格式乱了,所有的正文会变标题1,还给你自动编号,完全不知道从哪过来的。
找了很多办法,发现最有效的还是添加之后,手动再取出了,给他设置好格式,尤其是标题1、标题2这些
我的解决办法是这个:
if (obj is Paragraph sourcePara)
{
Paragraph newPara = sourcePara.Clone() as Paragraph;
Style existingStyle = targetDoc.Styles.FindByName(sourcePara.GetStyle().Name);
newSection.Body.ChildObjects.Add(newPara);
// 或者直接访问 Body 的最后一个子对象(需判断类型)
IDocumentObject lastObj = targetDoc.LastSection.Body.ChildObjects.LastItem;
if (lastObj is Paragraph)
{
Paragraph lastParaFinal = lastObj as Paragraph;
if (existingStyle != null)
{
lastParaFinal.ApplyStyle(existingStyle.Name);
}
}
}
当然这只处理了段落,表格处理思路也类似
else if (obj is Table sourceTable)
{
Table newTable = sourceTable.Clone() as Table;
var targetTableStyles = GetTableStyle(sourceTable, targetDoc);
newSection.Body.ChildObjects.Add(newTable);
IDocumentObject lastObj = targetDoc.LastSection.Body.ChildObjects.LastItem;
if (lastObj is Table lastTable)
{
SetTableStyle(lastTable, targetTableStyles);
}
}
就是把每个单元格的样式存起来,给加入到目标文段的段落ApplyStyle