publicstaticboolUpdateTableStyle(stringfilePath)
{
try
{
Document doc = newDocument();
//样式
Style style = doc.Styles.Add(StyleType.Paragraph, “cellStyle”);
style.Font.Name = “simsun”;
PageSetup pageSet = doc.Sections[0].PageSetup;
pageSet.PaperSize = PaperSize.A4;
pageSet.LeftMargin = ConvertUtil.MillimeterToPoint(5);
pageSet.RightMargin = ConvertUtil.MillimeterToPoint(5);
//pageSet.PageStartingNumber = 1;
//pageSet.PageNumberStyle = NumberStyle.Arabic;
DocumentBuilder builder = newDocumentBuilder(doc);
builder.MoveToHeaderFooter(HeaderFooterType.FooterPrimary);
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
//builder.InsertField(“PAGE”, “”);
//builder.Write(“/”);
//builder.InsertField(“NUMPAGES”, “”);
doublecellWidth = 18;
doubleportraitMinWidth = ConvertUtil.MillimeterToPoint(cellWidth);//纵向最小列宽
doublepageWidth = 200d;//A4纵向可编辑区域宽度200毫米//A4横向向可编辑区域宽度290毫米
List docItemList = newList();
boolIsLandscape = false;//是否为横向
//先计算是使用横向还是纵向的A4
if(File.Exists(filePath))
{
Document docItem = newDocument(filePath);
docItemList.Add(docItem);
vartableList = docItem.GetChildNodes(NodeType.Table, true);
boolisExist = false;
foreach(Table table intableList)
{
if(table.Range != null&& table.Range.Bookmarks != null)
{
foreach(Bookmark bkName intable.Range.Bookmarks)
{
if(bkName.Name == “aa”)
{
isExist = true;
break;
}
}
}
if(isExist)
{
//先计算是否符合纵向A4纸要求的列宽
doublewidth = ConvertUtil.MillimeterToPoint(200d / table.Rows[2].Cells.Count);
if(width < portraitMinWidth)
{
portraitMinWidth = width;
}
}
}
//不包含指标书签时,退出
if(!isExist)
returnfalse;
}
//如果列宽小于一定宽度那么就将文档变为横向cellWidth
if(portraitMinWidth < ConvertUtil.MillimeterToPoint(cellWidth))
{
IsLandscape = true;
pageWidth = 150d;
}
else
{
IsLandscape = false;
pageWidth = 120d;
}
inti = 1;
foreach(Document docItem indocItemList)
{
builder.MoveToDocumentEnd();
// Document docItem = new Document(path);
PageSetup pageSet1 = docItem.Sections[0].PageSetup;
pageSet1.PaperSize = PaperSize.A4;
pageSet1.LeftMargin = ConvertUtil.MillimeterToPoint(20);
pageSet1.RightMargin = ConvertUtil.MillimeterToPoint(20);
vartableList = docItem.GetChildNodes(NodeType.Table, true);
foreach(Table table intableList)
{
table.AutoFit(AutoFitBehavior.FixedColumnWidths);
foreach(Row row intable.Rows)
{
if(table.Range != null&& table.Range.Bookmarks != null)
{
foreach(Bookmark bkName intable.Range.Bookmarks)
{
if(bkName.Name == “aa”)
{
for(intj = 0; j < row.Cells.Count; j++)
{
row.Cells[j].CellFormat.WrapText = true;
doublewidth = ConvertUtil.MillimeterToPoint((pageWidth) / row.Cells.Count);
row.Cells[j].CellFormat.Width = width;
}
break;
}
}
}
}
}
docItem.FirstSection.HeadersFooters.LinkToPrevious(true);
builder.InsertDocument(docItem, ImportFormatMode.UseDestinationStyles);
i++;
}
if(IsLandscape)
{
//文档变为横向
pageSet.Orientation = Aspose.Words.Orientation.Landscape;
}
//重新整理页面布局
doc.UpdatePageLayout();
doc.Save(filePath);
returntrue;
}
catch(Exception ex)
{
LogHelper.WriteLog(“更新表格列宽异常,”, ex);
returnfalse;
}
}