欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

OpenXml合并Table单元格代码实例

程序员文章站 2022-06-21 20:29:46
using documentformat.openxml; using documentformat.openxml.packaging; using docu...
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();
      }

    }
    

  }
}

OpenXml合并Table单元格代码实例

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

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