PDF转WORD开发分享系列---DocX设置Word表格单元格宽度

Posted by 代码苦力 on August 28, 2014

DocX设置Word表格宽度

PDF转WORD是极具商业价值的开发项目, 但是其开发工作难度不小. PDF文件格式不是一般的复杂, 其文件格式文档就有一千多页, WORD文件的格式也不是一般的复杂, 而且不只是复杂, 其文件格式是不公开的, 要自己操作WORD文件那不是一般的难. 所以很多涉及到WORD文件操作的项目会用到DocX来进行WORD文件操作.
 
本节主要讲解如何用DocX设置Word表格单元格宽度, 该方法可用于C#, VC等等. 废话不多说, 先上一段代码, 代码如下:
 
internal static XElement CreateTable(int rowCount, int columnCount)
{
int[] columnWidths = new int[columnCount];
for (int i = 0; i < columnCount; i++)
{
columnWidths[i] = 2310;
}
return CreateTable(rowCount, columnWidths);
}
 
internal static XElement CreateTable(int rowCount, int[] columnWidths)
 {
     XElement newTable =
     new XElement
     (
         XName.Get("tbl", DocX.w.NamespaceName),
         new XElement
         (
             XName.Get("tblPr", DocX.w.NamespaceName),
                 new XElement(XName.Get("tblStyle", DocX.w.NamespaceName), new XAttribute(XName.Get("val", DocX.w.NamespaceName), "TableGrid")),
                 new XElement(XName.Get("tblW", DocX.w.NamespaceName), new XAttribute(XName.Get("w", DocX.w.NamespaceName), "5000"), new XAttribute(XName.Get("type", DocX.w.NamespaceName), "auto")),
                 new XElement(XName.Get("tblLook", DocX.w.NamespaceName), new XAttribute(XName.Get("val", DocX.w.NamespaceName), "04A0"))
         )
     );
 
     XElement tableGrid = new XElement(XName.Get("tblGrid", DocX.w.NamespaceName));
     for (int i = 0; i < columnWidths.Length; i++)
         tableGrid.Add(new XElement(XName.Get("gridCol", DocX.w.NamespaceName), new XAttribute(XName.Get("w", DocX.w.NamespaceName), XmlConvert.ToString(columnWidths[i]))));
 
     newTable.Add(tableGrid);
 
     for (int i = 0; i < rowCount; i++)
     {
         XElement row = new XElement(XName.Get("tr", DocX.w.NamespaceName));
 
         for (int j = 0; j < columnWidths.Length; j++)
         {
             XElement cell = CreateTableCell();
             row.Add(cell);
         }
 
         newTable.Add(row);
     }
     return newTable;
 }
 
如上代码, Docx实现代码里有两个CreateTable, 其一是: CreateTable(int rowCount, int columnCount), 其二是: CreateTable(int rowCount, int[] columnWidths). 开始我以为用第二个CreateTable并传进Column Width便可以控制表格的宽度, 然而经过各种调试均以失败而告终, 最后通过设置每个单元格的宽度实现了表格宽度的控制, 如下代码可设置表格第一列宽度为200, 第二列表格宽度为500:
 
table.Rows[0].Cells[0].Width = 200;
table.Rows[0].Cells[0].Width = 200;
table.Rows[1].Cells[1].Width = 500;
table.Rows[1].Cells[1].Width = 500;
 

Editor's Picks