使用破解版的Aspose.Words做操作。操作模式为
Document doc = new Document(FileInf.FullName);
// Table TableMain = doc.GetChildNodes(NodeType.Table, true)[0] as Table;
Document DocSetOut = null;// = new Document();
Aspose.Words.Layout.LayoutCollector layoutCollector = new Aspose.Words.Layout.LayoutCollector(doc);
int a = doc.BuiltInDocumentProperties.Pages;
DocumentPageSplitter splitter = new DocumentPageSplitter(layoutCollector);//将word文件分页
Document FirstPage = splitter.GetDocumentOfPage(1);
bool IsSinglePage = FirstPage.GetChildNodes(NodeType.Table, true).Count >0;//获取第一页是否有表格如果有表格就是循环读取,如果没有则是只获取第三页的数据
插入段落
DocumentBuilder buidone = new DocumentBuilder(Doc); 创建段落
Shape shape = buidone.InsertImage(ImgBit,ImgBit.Width,ImgBit.Height);//new Shape(Doc, ShapeType.Image);
shape.HorizontalAlignment = Aspose.Words.Drawing.HorizontalAlignment.Left;//左对齐
shape.WrapType = WrapType.None ;//.Square;
其中 shape.wrpatype 所获取的 WrapType.None 没有样式类似不占用现有空间于把随便移动衬于文字下方。through穿越的意思,同样会占用控件以及空间会产生一个空格。square占用方格空间不会有多余的空格。TopBottom顶头 后光标会转移到当前段落下面。inline嵌入型。Tight紧密型。微软官方指引:https://docs.microsoft.com/zh-cn/dotnet/api/microsoft.office.interop.word.wdwraptype?redirectedfrom=MSDN&view=word-pia
获取行数据
/// <summary>
/// 从表格中获取数据
/// </summary>
/// <param name="doc">单页文件</param>
/// <returns></returns>
public static ReportMain TabelToClass(Document doc,ReportMain Model)
{
if (doc != null)
{
//if (doc.FirstSection.Body.ChildNodes.Count<2)
//{
// MessageBox.Show("此文件无法解析,请更换模板。");
// return null;
//}
Model.HeadName ="";//获取第一个段落的body里的childnode的值获取表头
foreach (Node onenode in doc.FirstSection.Body.ChildNodes)
{
string HeadStr = onenode.GetText().Trim().Replace(" ","");
if(HeadStr.Contains("报告")&&HeadStr.Length<30)
{
Model.HeadName = HeadStr;
break;
}
}
if(Model.HeadName=="")
{
MessageBox.Show("此文件无法解析,请更换模板。");
return null;
}
if (doc.GetChildNodes(NodeType.Table, true).Count > 0)
{
Table Tb = doc.GetChildNodes(NodeType.Table, true)[0] as Table;//以表格模式获取导数据,然后进行解析
foreach (Row oneRow in Tb.Rows)
{
for (int i = 0; i < oneRow.Cells.Count; i++)
{
string cellValue = oneRow.Cells[i].GetText();
cellValue = cellValue.Replace("\a", "");
cellValue = cellValue.Replace("\r", "");
var dtype = Model.GetType();
foreach (PropertyInfo onePro in dtype.GetProperties())
{
string DESStr = "Nothing";
// DescriptionAttribute[] des = (DescriptionAttribute[])onePro.GetCustomAttributes(typeof(DescriptionAttribute), false);// 属性值
if ((DescriptionAttribute)Attribute.GetCustomAttribute(onePro, typeof(DescriptionAttribute)) != null) //当描述属性没有时,直接返回名称
{
DESStr = ((DescriptionAttribute)Attribute.GetCustomAttribute(onePro, typeof(DescriptionAttribute))).Description;
}
cellValue = cellValue.Replace(" ", "");//去除字段中的空格
if (cellValue.Contains(DESStr)&&cellValue.Length<40)
{
string CellNextText = oneRow.Cells[i + 1].GetText();
CellNextText = CellNextText.Replace("\a", "");
CellNextText = CellNextText.Replace("\r", "");
onePro.SetValue(Model, CellNextText, null);
}
}
}
}
}
}
return Model;
}