在MS Words中,为了使表格中的列自动适合内容,我们单击表格。在“布局”选项卡上的“单元格大小”组中,单击“自动调整”,然后单击“自动调整内容”。
对内容应用自动调整后,结果如下:
我正在使用 Microsoft Open XML SDK 来实现上述功能。我创建了一种按列对表格单元格进行分组的方法,然后将每个列的宽度设置为最大单元格内容长度。
但问题是,一些单元格要么水平合并,要么垂直合并(这就是我的主要问题),使我的解决方案绝对失败。我到处搜索,但没有找到有用的资源
经过几天的广泛搜索,我已经耗尽了我的努力,决定通过在这个论坛上提出我的问题来寻求帮助。在熟悉了论坛的提问指南后,我现在提出我的疑问并请求解决方案的建议。
我终于找到解决办法了。
根据有关表的 Open Office XML 文档,详细说明如下: http://officeopenxml.com/WPtableLayout.php :
因此,基本上将我的表格属性 TableLayout 和 TableWidth 属性设置为 AutoFit 和 Auto 就可以了。
我还需要进行的另一项更改是将表格和单元格的宽度和类型设置为“0”和“自动”,就像在使用“自动调整内容”选项时在 MS Words 中一样。
这是我的最终解决方案:
public static class OpenXmlAutoFit
{
public static void AutoFitToContent( string filePath, string copyPath )
{
// Check if the source file exists
if( File.Exists( filePath ) )
{
// Check if the copy file already exists
if( File.Exists( copyPath ) )
{
// Delete the existing copy file
File.Delete( copyPath );
}
// Create a new copy of the file
File.Copy( filePath, copyPath );
}
using( WordprocessingDocument doc = WordprocessingDocument.Open( copyPath, true ) )
{
MainDocumentPart mainPart = doc.MainDocumentPart;
IEnumerable<DocumentFormat.OpenXml.Wordprocessing.Table> tables = mainPart.Document.Descendants<DocumentFormat.OpenXml.Wordprocessing.Table>();
// var tables = mainPart.Document.Body.Elements<DocumentFormat.OpenXml.Drawing.Table>();
// var tables = mainPart.Document.Body.Descendants<Table>();
foreach( var table in tables )
{
if( table != null )
{
// Get the table properties element
TableProperties tableProperties = table.GetFirstChild<TableProperties>();
// If table properties exist, update them; otherwise, create new table properties
if( tableProperties != null )
{
// Update existing table properties
tableProperties.TableLayout = new TableLayout { Type = TableLayoutValues.Autofit };
tableProperties.TableWidth = new TableWidth { Type = TableWidthUnitValues.Auto };
}
else
{
// Create new table properties and add them to the table
tableProperties = new TableProperties(
new TableLayout { Type = TableLayoutValues.Autofit },
new TableWidth { Type = TableWidthUnitValues.Auto }
);
table.PrependChild( tableProperties );
}
var tableWidths = table.Descendants<DocumentFormat.OpenXml.Wordprocessing.TableWidth>().ToList();
foreach( var tblW in tableWidths )
{
tblW.Width = "0";
tblW.Type = DocumentFormat.OpenXml.Wordprocessing.TableWidthUnitValues.Auto;
}
var tableCellsWidths = table.Descendants<DocumentFormat.OpenXml.Wordprocessing.TableCellWidth>().ToList();
foreach( var tcW in tableCellsWidths )
{
tcW.Width = "0";
tcW.Type = DocumentFormat.OpenXml.Wordprocessing.TableWidthUnitValues.Auto;
}
}
}
mainPart.Document.Save();
}
}
}