使用OpenXml向空白文档添加一个带表格线的表(转)

时间:2022-08-09 20:26:57
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Packaging;

using System.Linq;
using System.Text;
using System.Xml;

using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Wordprocessing;
using DocumentFormat.OpenXml.Packaging;

namespace HelloDocx
{
class Program
{
static void Main(string[] args)
{
using(WordprocessingDocument doc = WordprocessingDocument.Create("D:\\Test.docx", WordprocessingDocumentType.Document))
{
MainDocumentPart mainPart = doc.AddMainDocumentPart();
mainPart.Document = new Document();
Body body = mainPart.Document.AppendChild(new Body());

Paragraph p = mainPart.Document.Body.AppendChild(new Paragraph());
p.AppendChild(new Run(new Text("Test")));

CreateTable(doc);
}

}

private static bool CreateTable(WordprocessingDocument doc)
{
bool result = false;
Table tab = new Table();
TableProperties tbps = new TableProperties();
TableWidth tbwidth = new TableWidth()
{
Width = "0",
Type = TableWidthUnitValues.Auto
};
TableBorders tbbs = new TableBorders();
TopBorder tpb = new TopBorder()
{
Val = BorderValues.Single
};
BottomBorder tbb = new BottomBorder()
{
Val = BorderValues.Single
};
RightBorder trb = new RightBorder()
{
Val = BorderValues.Single
};
LeftBorder tlb = new LeftBorder()
{
Val = BorderValues.Single
};
InsideHorizontalBorder tihb = new InsideHorizontalBorder()
{
Val = BorderValues.Single
};
InsideVerticalBorder tivb = new InsideVerticalBorder()
{
Val = BorderValues.Single
};
tbbs.Append(tpb);
tbbs.Append(tbb);
tbbs.Append(trb);
tbbs.Append(tlb);
tbbs.Append(tihb);
tbbs.Append(tivb);
tbps.Append(tbbs);
tbps.Append(tbwidth);
TableGrid TG = new TableGrid();
GridColumn GC1 = new GridColumn() { Width = "3192" };
GridColumn GC2 = new GridColumn() { Width = "3192" };
GridColumn GC3 = new GridColumn() { Width = "3192" };
TG.Append(GC1);
TG.Append(GC2);
TG.Append(GC3);
TableRow TR1 = new TableRow();
TableCell TC1 = new TableCell();
AddTableCellProperty(TC1);
Paragraph P1 = new Paragraph();
TC1.Append(P1);
TableCell TC2 = new TableCell();
AddTableCellProperty(TC2);
Paragraph P2 = new Paragraph();
TC2.Append(P2);
TableCell TC3 = new TableCell();
AddTableCellProperty(TC3);
Paragraph P3 = new Paragraph();
TC3.Append(P3);
TR1.Append(TC1);
TR1.Append(TC2);
TR1.Append(TC3);
tab.Append(tbps);
tab.Append(TG);
tab.Append(TR1);
doc.MainDocumentPart.Document.Body.Append(tab);
result = true;
return result;
}

private static void AddTableCellProperty(TableCell TC)
{
TableCellProperties TCP = new TableCellProperties();
TableCellWidth TCW = new TableCellWidth()
{
Width = "3192",
Type = TableWidthUnitValues.Dxa
};
TCP.Append(TCW);
TC.Append(TCP);
}
}
}


转自:http://blog.csdn.net/songpengpeng20100202/article/details/7426733

ps:调用处与原文稍微变动,但创建表的函数无修改