OpenXml合并Table单元格代码实例

所属分类: 软件编程 / C#教程 阅读数: 105
收藏 0 赞 0 分享
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using OpenXML.Model;
using System;
using System.Collections.Generic;

namespace OpenXML
{
  class Program
  {
    //表格数据
    public static List<List<string>> _tabData;

    public Program(List<List<string>> tabData) {
      _tabData = tabData;
    }

    static void Main(string[] args)
    {
      List<string> dataTitle = new List<string>() { "序号","姓名","性别"};
      List<string> data1 = new List<string>() { "1", "张三", "男" };
      List<string> data2 = new List<string>() { "2", "王五", "男" };
      List<string> data3 = new List<string>() { "3", "李四", "女" };

      _tabData = new List<List<string>>();
      _tabData.Add(dataTitle);
      _tabData.Add(data1);
      _tabData.Add(data2);
      _tabData.Add(data3);
      CreateTable(_tabData, @"C:\Users\dzw159\Desktop\WT\VS\OpenXMLFile\openXMLTest.docx",300);

      //CreateOpenXMLFile(@"C:\Users\dzw159\Desktop\WT\VS\OpenXMLFile\openXMLTest.docx");
      Console.WriteLine("Hello World!");
      Console.Read();
    }

    /// <summary>
    /// 创建Word
    /// </summary>
    /// <param name="filePath"></param>
    public static void CreateOpenXMLFile(string filePath)
    {
      using (WordprocessingDocument objWordDocument = WordprocessingDocument.Create(filePath, WordprocessingDocumentType.Document))
      {
        MainDocumentPart objMainDocumentPart = objWordDocument.AddMainDocumentPart();
        objMainDocumentPart.Document = new Document(new Body());
        Body objBody = objMainDocumentPart.Document.Body;
        //创建一些需要用到的样式,如标题3,标题4,在OpenXml里面,这些样式都要自己来创建的  
        //ReportExport.CreateParagraphStyle(objWordDocument); 
        SectionProperties sectionProperties = new SectionProperties();
        PageSize pageSize = new PageSize();
        PageMargin pageMargin = new PageMargin();
        Columns columns = new Columns() { Space = "220" };//720 
        DocGrid docGrid = new DocGrid() { LinePitch = 100 };//360 
                                  //创建页面的大小,页距,页面方向一些基本的设置,如A4,B4,Letter,  
                                  //GetPageSetting(PageSize,PageMargin); 

        //在这里填充各个Paragraph,与Table,页面上第一级元素就是段落,表格. 
        objBody.Append(new Paragraph());
        objBody.Append(new Table());
        objBody.Append(new Paragraph());

        //我会告诉你这里的顺序很重要吗?下面才是把上面那些设置放到Word里去.(大家可以试试把这下面的代码放上面,会不会出现打开openxml文件有误,因为内容有误) 
        sectionProperties.Append(pageSize, pageMargin, columns, docGrid);
        objBody.Append(sectionProperties);

        //如果有页眉,在这里添加页眉. 
        //if (IsAddHead)
        //{
          //添加页面,如果有图片,这个图片和上面添加在objBody方式有点不一样,这里搞了好久. 
          //ReportExport.AddHeader(objMainDocumentPart, image); 
        //}
        objMainDocumentPart.Document.Save();
      }
    }

    /// <summary>
    /// 创建Tab
    /// </summary>
    /// <param name="tabData"></param>
    /// <param name="filePath"></param>
    /// <param name="width"></param>
    public static void CreateTable(List<List<string>> tabData, string filePath,int width)
    {
      //打开Word文件
      using (WordprocessingDocument d = WordprocessingDocument.Open(filePath,true))
      {
        //声明表格
        Table tab = new Table();
        //表格样式
        TableProperties tblProp = new TableProperties(new TableBorders(
          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 }
          )
        ));

        //设置表格宽度
        tblProp.TableWidth = new TableWidth() { Width = width.ToString(), Type = TableWidthUnitValues.Dxa };
        //样式添加
        tab.Append(tblProp);

        int j = 0;
        //循环生成单元格
        foreach (var item in tabData)
        {
          //声明Tab行
          TableRow row = new TableRow();
          for (var i = 0; i < item.Count; i++)
          {
            //申明单元格
            TableCell cell = new TableCell();

            TableCellProperties tableCellProperties = new TableCellProperties();
            //单元格样式设置
            TableCellMargin margin = new TableCellMargin();
            margin.LeftMargin = new LeftMargin() {
              Width="100",
              Type = TableWidthUnitValues.Dxa
            };
            margin.RightMargin = new RightMargin()
            {
              Width = "100",
              Type = TableWidthUnitValues.Dxa
            };
            tableCellProperties.Append(margin);

            Paragraph par = new Paragraph();
            Run run = new Run();


            //如果同一列的参数相同(合并单元格)
            if (j < (tabData.Count - 1) && item[i] == tabData[j + 1][i])
            {
              VerticalMerge verticalMerge = new VerticalMerge() {
                Val = MergedCellValues.Restart
              };
              //RunProperties rpr = new RunProperties();
              //rpr.Append(new Bold());
              //run.Append(rpr);
              //verticalMerge.Val = MergedCellValues.Restart;
              //Text t = new Text(item[i]);
              //t.Space = new EnumValue<SpaceProcessingModeValues>(SpaceProcessingModeValues.Preserve);

              //run.Append(t);

              TableCellProperties tableCellProperties2 = new TableCellProperties();
              tableCellProperties2.Append(verticalMerge);
              cell.Append(tableCellProperties2);
              Text t = new Text(item[i]);
              t.Space = new EnumValue<SpaceProcessingModeValues>(SpaceProcessingModeValues.Preserve);
              run.Append(t);
            }
            //和上一行比较(合并单元格)
            else if (j>0 && j < (tabData.Count) && item[i] == tabData[j -1][i])
            {

              VerticalMerge verticalMerge = new VerticalMerge()
              {
                Val = MergedCellValues.Continue
              };
              TableCellProperties tableCellProperties2 = new TableCellProperties();
              tableCellProperties2.Append(verticalMerge);
              cell.Append(tableCellProperties2);
              Text t = new Text(item[i]);
              t.Space = new EnumValue<SpaceProcessingModeValues>(SpaceProcessingModeValues.Preserve);
              run.Append(t);
            }
            else
            {
              //RunProperties rPr = new RunProperties();
              //rPr.Append(new Bold());
              //run.Append(rPr);

              //单元格内容添加(由内向外顺序)
              Text t = new Text(item[i]);
              t.Space = new EnumValue<SpaceProcessingModeValues>(SpaceProcessingModeValues.Preserve);
              run.Append(t);
            }
            par.Append(run);
            cell.Append(tableCellProperties);
            cell.Append(par);
            row.Append(cell);

          }
          j++;
          //表格添加行
          tab.Append(row);
        }
        //objBody.Append(new Paragraph());
        //objBody.Append(new Table());
        

        d.MainDocumentPart.Document.Body.Append(new Paragraph(new Run(tab)));
        d.MainDocumentPart.Document.Save();
      }

    }
    

  }
}

注:他们有的说,标记为MergedCellValues.Continue的纵向单元格一定要给值!(这个我试着给赋值null或者为“”,都能正常合并)

以上就是全部知识点内容,感谢大家的阅读和对脚本之家的支持。

更多精彩内容其他人还在看

C# 全角和半角转换以及判断的简单代码

这篇文章介绍了在C#中判断和转换全角半角的方法,有需要的朋友可以参考一下
收藏 0 赞 0 分享

解析C#中如何把控件的边框角画为圆弧

以下是对C#中把控件的边框角画为圆弧的实现代码进行了介绍,需要的朋友可以参考下
收藏 0 赞 0 分享

如何清空文件夹里面的所有文件和文件夹

以下是对c#中清空文件夹里面的所有文件和文件夹的实现代码进行了详细的分析介绍,需要的朋友可以参考下
收藏 0 赞 0 分享

如何让C#、VB.NET实现复杂的二进制操作

VB.NET和C#属于高级语言,对二进制位操作的支持不是很好,比如没有了移位运算等,用的时候确实很不方便,所以在闲暇之余我重新封装了一个用于C#、VB.NET的位操作类库,通过该类库可以实现数据移位、循环移位、转换为二进制、将二进制转换为数据等
收藏 0 赞 0 分享

C# 中如何利用lambda实现委托事件的挂接

在写一个小程序的时候,碰到了这样的问题,需要用委托来挂接事件,但是又想在这事件中使用局部的变量,而委托一旦定义好后,挂接方就没有办法再添加额外的形参了。那有没有什么办法,可以实现呢
收藏 0 赞 0 分享

C#技巧之快速删除bin和obj文件夹的方法

C#程序总会生成bin和obj文件夹,为了减小源码的大小,就有必要将这两个文件夹删除,于是想到用批处理文件来删除
收藏 0 赞 0 分享

C#编程实现Excel文档中搜索文本内容的方法及思路

有了在Word文档中编程实现搜索文本的经验,在Excel中实现这个功能也并非难事。
收藏 0 赞 0 分享

C#根据年月日计算星期几的函数小例子

这篇文章介绍了C#根据年月日计算星期几的函数小例子,有需要的朋友可以参考一下
收藏 0 赞 0 分享

c# 空合并运算符“??”的使用详解

本篇文章是对c#中空合并运算符“??”的使用进行了详细的分析介绍,需要的朋友参考下
收藏 0 赞 0 分享

浅谈c# 泛型类的应用

本篇文章是对c#中泛型类的应用进行了详细的分析介绍,需要的朋友参考下
收藏 0 赞 0 分享
查看更多