不知道大家操作docx文件时,有没有遇见过以下两个问题:
1、6.5.0版本:操作docx文件后,程序保存再打开会将新罗马字体的空格自动格式化为换行。
2、16.7.0版本:操作docx文件,会将行间距变大。将段后间距自动增加10,设置成多倍行距。
上面两个问题困惑了很久,找了很多方法和版本的dll尝试。
最后得出的结果是,Aspose.Words.dll 19.11版本以下的好像都有行间距的问题,但是我去官网搜搜高本版需要收费。最后找到的两个解决途径是:
1、手工打开docx文件,另存为doc格式,然后操作.doc文件。注意直接修改后缀名不行。我也尝试用程序直接保存为doc文件,也不可以。
2、处理行间距,设置单倍行距、段后间距设置成0,如下。
/// <summary>
/// 设置段落格式(行间距)
/// </summary>
/// <param name="parFormat"></param>
private static void SetParagraphFormat(ParagraphFormat parFormat)
{
//设置所有段落的格式
parFormat.LineSpacingRule = LineSpacingRule.AtLeast;//单倍行距
parFormat.SpaceBefore = float.Parse("0.0");//段前间距
parFormat.SpaceBeforeAuto = false;//
parFormat.SpaceAfter = float.Parse("0.0");//段后间距
parFormat.SpaceAfterAuto = false;
}
3、如果单一的设置某个段落,获取到指定段落位置,使用上面代码即可。
但是想要通篇整个文档批量处理,就需要循环获取所有页面的段落、表格、单元格等类型的段落格式。
/// <summary>
/// 设置全文段落格式
/// </summary>
/// <param name="doc"></param>
private static void SetDocumentParagraphFomat(Document doc)
{
foreach (Section srcSection in doc.Sections)
{
foreach (Object srcNode in srcSection.Body)
{
if (((Node)srcNode).NodeType == NodeType.Paragraph)//段落
{
Paragraph para = (Paragraph)srcNode;
SetParagraphFormat(para.ParagraphFormat);
}
else if (((Node)srcNode).NodeType == NodeType.Table)//表格
{
Table Tab = (Table)srcNode;
if (Tab == null) continue;
// Tab.AutoFit(AutoFitBehavior.AutoFitToWindow);//表格适应窗口大小
for (int i = 0; i < Tab.Rows.Count; i++)//行
{
if (Tab.Rows[i] == null) continue;
for (int j = 0; j < Tab.Rows[i].Cells.Count; j++)//单元格
{
if (Tab.Rows[i].Cells[j] == null) continue;
Cell cell = Tab.Rows[i].Cells[j];//获取到单元格
if (cell == null) continue;
if (Tab.Rows[i].Cells[j].Paragraphs != null)
{
int cpcount = Tab.Rows[i].Cells[j].Paragraphs.Count;
for (int k = 0; k < cpcount; k++)
{
if (Tab.Rows[i].Cells[j].Paragraphs[k] == null) continue;
SetParagraphFormat(Tab.Rows[i].Cells[j].Paragraphs[k].ParagraphFormat);
}
}
else
{
Node cellContent = cell.GetChild(NodeType.Paragraph, 0, false);
if (cellContent == null) continue;
Paragraph cp = (Paragraph)cellContent;
SetParagraphFormat(cp.ParagraphFormat); //设置所有段落的格式
}
}
}
}
}
}
}