在日常开放中经常会遇到各种操作word中的表格问题,或者基于word模板生成word等等操作。微软得com组件挺好但是必须要安装office对于客户来说很麻烦,而且效率很慢。推荐使用openxml~,但是使用openxml比较烦,各种操作繁琐,但相对与com组件无需安装,速度快就是它得优势~以下代码
/// <summary>
/// 生成表格
/// </summary>
/// <param name="reportTable"></param>
/// <param name="width"></param>
/// <returns></returns>
public Table GetParagraph(OpenxmlTableModel reportTable, Int32Value width)
{
Table table = new Table();
TableProperties tblProp = new TableProperties(
new TableBorders(
new TopBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4 },
new BottomBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4 },
new LeftBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4 },
new RightBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4 },
new InsideHorizontalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4 },
new InsideVerticalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4 }
)
)
{
//A4表格 4835左右
TableWidth = new TableWidth() { Width = width.ToString(), Type = TableWidthUnitValues.Pct },
};
table.Append(tblProp);
int cols = reportTable.Column;
int j = 0;
foreach (List<OpenxmlTableModel.StrText> strs in reportTable.Value)
{
int merge = 0;
bool startMerge = true;
TableRow row = new TableRow();
for (int i = 0; i < cols; i++)
{
merge = merge > 0 ? merge : strs[i].Merges;
TableCell cell = new TableCell();
//单元格属性
TableCellProperties tableCellProperties = new TableCellProperties();
//段落属性
Paragraph par = new Paragraph();
//边距
TableCellMargin margin = new TableCellMargin
{
LeftMargin = new LeftMargin() { Width = "0", Type = TableWidthUnitValues.Auto },
RightMargin = new RightMargin() { Width = "0", Type = TableWidthUnitValues.Auto }
};
tableCellProperties.Append(margin);
//垂直居中,将属性加入到单元格样式段落样式
tableCellProperties.Append(new TableCellVerticalAlignment { Val = TableVerticalAlignmentValues.Center });
par.Append(new ParagraphProperties(new Justification() { Val = JustificationValues.Center }));
Run run = new Run();
//表头
if (j == 0 && reportTable.IsHaveHeader)
{
RunProperties rPr = new RunPro