工作中遇到处理word模板用到了aspose插件,其中遇到了合并单元格,其中分为上下单元格合并,以及左右单元格合并

1.一行中相邻单元格合并

 //合并所有左右相邻单元格一致的行public static void hbCells( HashMap<String,Object> m1,String filepath ) throws Exception{Map rs=getcf(m1);Iterator iterator = rs.keySet().iterator(); Map rr = new HashMap();//获取重复数据的合并行的坐标while (iterator.hasNext()){ Object value = iterator.next(); List<String> result = (List) rs.get(value); //System.out.println(result);List list = new ArrayList();List<Integer> rowlist = new ArrayList<Integer>();List<Integer> celllist = new ArrayList<Integer>();for( String js:result){String jj= getTextCellRow(filepath,js); int row=Integer.parseInt(jj.split(",")[0]);int cell=Integer.parseInt(jj.split(",")[1]);rowlist.add(row);celllist.add(cell);}list=getCellQJ(rowlist,celllist);if(list.size()>0){rr.put(value, list);}}//2处理合并Iterator ite = rr.keySet().iterator(); while (ite.hasNext()){ Object value = ite.next(); List<String> result = (List) rr.get(value); hbCell(filepath,result,filepath);}}public static List<String> getCellQJ(List<Integer> rowList,List<Integer> cellList) throws Exception{List<String> list = new ArrayList<String>();int maxrow= Collections.max(rowList);int maxcell= Collections.max(cellList);int minrow= Collections.min(rowList);int mincell= Collections.min(cellList);if(maxrow==minrow){int size=rowList.size();int fw=maxcell-mincell+1;//连续的单元格if(size==fw){list.add(mincell+","+minrow);list.add(maxcell+","+minrow);}}return list;}//合并左右单元public static void hbCell( String filepath, List<String> result,String savefile) throws Exception{int row=Integer.parseInt(result.get(0).split(",")[1]);int mincell=Integer.parseInt(result.get(0).split(",")[0]);int maxCell=Integer.parseInt(result.get(1).split(",")[0]);Document doc = new Document(filepath);Table table = (Table) doc.getChild(NodeType.TABLE, 0, true); //第1个表格// We want to merge the range of cells found in between these two cells.Cell cellStartRange = table.getRows().get(row).getCells().get(mincell); //第2行第1列Cell cellEndRange = table.getRows().get(row).getCells().get(maxCell); //第3行第1列// Merge all the cells between the two specified cells into one.mergeCellshx(cellStartRange, cellEndRange);doc.save(savefile);}//合并一行的相邻单元格public static void mergeCellshx(Cell startCell, Cell endCell) {Table parentTable = startCell.getParentRow().getParentTable();double Cellwidth=0;;//Table parentTable2 = endCell.getParentRow().getParentTable();// Find the row and cell indices for the start and end cell.Point startCellPos = new Point(startCell.getParentRow().indexOf(startCell), parentTable.indexOf(startCell.getParentRow()));Point endCellPos = new Point(endCell.getParentRow().indexOf(endCell), parentTable.indexOf(endCell.getParentRow()));// Create the range of cells to be merged based off these indices. Inverse each index if the end cell if before the start cell.Rectangle mergeRange = new Rectangle(Math.min(endCellPos.x, startCellPos.x),Math.min(endCellPos.y, endCellPos.y),Math.abs(endCellPos.x-startCellPos.x)+1 ,1);//1,2,0,18 h,w,x,yfor (Row row : parentTable.getRows()) {for (Cell cell : row.getCells()) {Point currentPos = new Point(row.indexOf(cell), parentTable.indexOf(row));// Check if the current cell is inside our merge range then merge it.0,18  1,18if (mergeRange.contains(currentPos)) { Cellwidth+= cell.getCellFormat().getWidth();if (currentPos.y == mergeRange.y)cell.getCellFormat().setVerticalMerge(CellMerge.FIRST);elsecell.getCellFormat().setVerticalMerge(CellMerge.NONE);if (currentPos.x==mergeRange.x)cell.getCellFormat().setHorizontalMerge(CellMerge.FIRST);elsecell.getCellFormat().setHorizontalMerge(CellMerge.PREVIOUS);}}}startCell.getCellFormat().setWidth(Cellwidth);}

2.处理合并上下单元格

//合并所有上下单元格一致的行public static void hbRows( HashMap<String,Object> m1,String filepath ) throws Exception{Map rs=getcf(m1);Iterator iterator = rs.keySet().iterator(); Map rr = new HashMap();Map cr = new HashMap();//获取重复数据的合并行的坐标while (iterator.hasNext()){ Object value = iterator.next(); List<String> result = (List) rs.get(value); //System.out.println(result);List listr = new ArrayList();List listc = new ArrayList();List<Integer> rowlist = new ArrayList<Integer>();List<Integer> celllist = new ArrayList<Integer>();for( String js:result){String jj= getTextCellRow(filepath,js); if(StringUtils.isNotEmpty(jj)){int row=Integer.parseInt(jj.split(",")[0]);int cell=Integer.parseInt(jj.split(",")[1]);rowlist.add(row);celllist.add(cell);}}if(rowlist.size()>0){listr=getRowQJ(rowlist,celllist);if(listr.size()>0){rr.put(value, listr);}listc=getCellQJ(rowlist,celllist);if(listc.size()>0){cr.put(value, listc);}}}//2处理合并//1.合并上下相同的单元格Iterator ite = rr.keySet().iterator(); while (ite.hasNext()){ Object value = ite.next(); List<String> result = (List) rr.get(value); hbRow(filepath,result,filepath);}//2.合并左右相同的单元格Iterator itc = cr.keySet().iterator(); while (itc.hasNext()){ Object value = itc.next(); List<String> result = (List) cr.get(value); hbCell(filepath,result,filepath);}}//合并上下单元public static void hbRow( String filepath, List<String> result,String savefile) throws Exception{int minrow=Integer.parseInt(result.get(0).split(",")[0]);int cell=Integer.parseInt(result.get(0).split(",")[1]);int maxrow=Integer.parseInt(result.get(1).split(",")[0]);Document doc = new Document(filepath);Table table = (Table) doc.getChild(NodeType.TABLE, 0, true); //第1个表格// We want to merge the range of cells found in between these two cells.Cell cellStartRange = table.getRows().get(minrow).getCells().get(cell); //第2行第1列Cell cellEndRange = table.getRows().get(maxrow).getCells().get(cell); //第3行第1列// Merge all the cells between the two specified cells into one.mergeCells(cellStartRange, cellEndRange);doc.save(savefile);}//获取区间row大小必须列一致public static List<String> getRowQJ(List<Integer> rowList,List<Integer> cellList) throws Exception{List<String> list = new ArrayList<String>();int maxrow= Collections.max(rowList);int maxcell= Collections.max(cellList);int minrow= Collections.min(rowList);int mincell= Collections.min(cellList);if(maxcell==mincell){int size=rowList.size();int fw=maxrow-minrow+1;//连续的单元格if(size==fw){//只有第一列if(mincell==0){list.add(minrow+","+mincell);list.add(maxrow+","+mincell);}}}return list;}//获取相同value的keypublic static Map getcf(Map<String, Object> map){Map rs = new HashMap();Map values = new HashMap();List list = new ArrayList(); Iterator iterator = map.keySet().iterator(); while (iterator.hasNext()) { Object key = iterator.next(); Object value = map.get(key); if (map.containsValue(value)) { if (values.containsKey(value)) { list = (List) values.get(value); } else { list = new ArrayList(); } list.add(key); values.put(value, list); } } iterator = values.keySet().iterator(); while (iterator.hasNext()) { Object value = iterator.next(); List result = (List) values.get(value); if (result.size() > 1) { rs.put(value, result);// System.out.println("value :" + value + "  -> keys:" + result.toString()); } } return rs; }//获取内容的行列public static String getTextCellRow(String FilePath,String data) throws Exception{Document doc;String tt="";String s = "<License><Data><Products><Product>Aspose.Total for Java</Product><Product>Aspose.Words for Java</Product></Products><EditionType>Enterprise</EditionType><SubscriptionExpiry>20991231</SubscriptionExpiry><LicenseExpiry>20991231</LicenseExpiry><SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber></Data><Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature></License>";ByteArrayInputStream is = new ByteArrayInputStream(s.getBytes());License license = new License();license.setLicense(is);doc = new Document(FilePath);//替换表格//获取第一个表格Table table = (Table)doc.getChild(NodeType.TABLE, 0, true);if(table!=null){DocumentBuilder builder = new DocumentBuilder(doc);RowCollection rows = table.getRows();
//          System.out.println("rows==="+rows.getCount());for (int i = 0; i < rows.getCount(); i++) {Row row = rows.get(i);for(int j=0; j<row.getCells().getCount(); j++){Cell cell=row.getCells().get(j);if(null != cell ){String text = cell.getText().trim();if(null != text && !"".equals(text)){if(text.equals(data)){tt=i+","+j;}}                  }}}}return tt;}/**合并列* Merges the range of cells found between the two specified cells both* horizontally and vertically. Can span over multiple rows.* @param startCell* @param endCell*/public static void mergeCells(Cell startCell, Cell endCell) {Table parentTable = startCell.getParentRow().getParentTable();// Find the row and cell indices for the start and end cell.Point startCellPos = new Point(startCell.getParentRow().indexOf(startCell), parentTable.indexOf(startCell.getParentRow()));Point endCellPos = new Point(endCell.getParentRow().indexOf(endCell), parentTable.indexOf(endCell.getParentRow()));// Create the range of cells to be merged based off these indices. Inverse each index if the end cell if before the start cell.Rectangle mergeRange = new Rectangle(Math.min(startCellPos.x, endCellPos.x), Math.min(startCellPos.y, endCellPos.y), Math.abs(endCellPos.x-startCellPos.x) + 1,Math.abs(endCellPos.y-startCellPos.y) + 1);for (Row row : parentTable.getRows()) {for (Cell cell : row.getCells()) {Point currentPos = new Point(row.indexOf(cell), parentTable.indexOf(row));// Check if the current cell is inside our merge range then merge it.if (mergeRange.contains(currentPos)) {if (currentPos.x==mergeRange.x)cell.getCellFormat().setHorizontalMerge(CellMerge.FIRST);elsecell.getCellFormat().setHorizontalMerge(CellMerge.PREVIOUS);if (currentPos.y == mergeRange.y)cell.getCellFormat().setVerticalMerge(CellMerge.FIRST);elsecell.getCellFormat().setVerticalMerge(CellMerge.PREVIOUS);}}}}

3测试方法

合并map中value值相同的相邻单元格

String filepath="E://AAA//1.doc";

HashMap<String,Object> m1 = new HashMap<String,Object>();
            m1.put("1","黄");
            m1.put("11","黄");
            m1.put("3","涛");
            m1.put("4","涛");
            hbCells(m1,filepath);
            hbRows(m1,filepath);

4.文件的表格样式

5.合并之后

aspose合并单元格相关推荐

  1. aspose 换行写_Aspose.Cells 首次使用,用到模版填充数据,合并单元格,换行

    Aspose.Cells 首次使用,用到模版填充数据,合并单元格,换行 模版格式,图格式是最简单的格式,但实际效果不是这种,实际效果图如图2 image 图2 ,注意看红色部分,一对一是正常的,但是有 ...

  2. Aspose.Cells增加边框和合并单元格

    将datatable内容复制到excel模板中时,合并单元格操作 worksheet.Cells[起始行, 起始列, 结束行, 结束列].Merge = true; 增加边框 worksheet.Ce ...

  3. bootstraptable合并标题_bootstrapTable 合并单元格

    /** * 合并单元格 * @param data 原始数据(在服务端完成排序) * @param fieldName 合并属性名称 * @param colspan 合并列 * @param tar ...

  4. php td居中显示文字,【html】合并单元格,并居中显示文本

    现状: 想要实现的效果: 代码实现: 用例失败为0,无测试详情 知识点: 合并单元格 rowspan是合并行,colspan 是合并列 456 实例: 1 2 3 456 效果: 2.单元格内容居中: ...

  5. python 2x xlrd使用merged_cells 读取的合并单元格为空

    一个简单的excel 如下 代码如下 #!/usr/bin/python# # -*- coding: utf-8 -*- import xlrd import sys reload(sys) sys ...

  6. cxgrid中纵横单元格合并_被合并单元格折磨疯的我,真后悔没早点知道这个Excel技巧!...

    在大家日常的工作中,经常会用到Excel合并单元格,然而合并单元格其实只是美化了表格,它会使我们后续的统计工作遇到很多麻烦,今天就给大家提供两个解决这个问题的思路. 01 合并单元格的基本操作方法 在 ...

  7. 【合并单元格】纵向合并单元格之前对数组处理【针对饿了么element的table的span-method合并行或列的计算方法】

    <template><el-table :span-method="spanMethod"><el-table-column label=" ...

  8. ExtJs grid合并单元格

    extjs中,如果要输出一些有合并单元格的表格,要怎么做呢?如图所示: 从网上找了个例子,其主要思想是表格的store装载完毕后,随即对这个grid的td进行一个个的控制,用的方法也是原始的javas ...

  9. java excel导出 jxl_java使用JXL导出Excel及合并单元格

    jxl是一个韩国人写的java操作excel的工具,在开源世界中,有两套比较有影响的API可供使用,一个是POI,一个是jExcelAPI.其中功能相对POI比较弱一点.但jExcelAPI对中文支持 ...

  10. EasyUI DataGrid根据字段动态合并单元格

    为什么80%的码农都做不了架构师?>>>    1.合并方法 /** * EasyUI DataGrid根据字段动态合并单元格 * 参数 tableID 要合并table的id * ...

最新文章

  1. ubuntu16创建开机启动服务
  2. 十九、约束作用及常见约束
  3. 安装完matlab7.0但无法运行
  4. VTK:环境球AmbientSpheres用法实战
  5. SpringBoot集成Elasticsearch实现博客高亮搜索
  6. 【例题+习题】【数值计算方法复习】【湘潭大学】(一)
  7. python里面的数学
  8. Impala内存优化
  9. 关于整型和浮点型的输出问题
  10. 合肥科学岛安光所计算机应用,国家大气污染防治攻关联合中心成立 合肥科学岛安光所承担重任...
  11. 倍福TwinCAT软件安装及注意事项
  12. 朱利亚 matlab分形图,分形实例的赏析
  13. 创维广电服务器无线,创维酷开电视连接有线和无线上网教程
  14. Google Guava EventBus 消息发布-订阅异步调用使用
  15. 数据库迁移工具Kettle连接Mysql数据库报错:Driver class ‘org.gjt.mm.mysql.Driver‘ could not be found, make sure the解决
  16. Flutter路由管理和接收页面的返回值
  17. 2021qq匿名说说在哪里
  18. 推荐系统深度学习篇-NFM 模型介绍(1)
  19. 痛苦的时候,不妨默读“有容乃大”
  20. 红米note4x开启root权限

热门文章

  1. Contextual 上下文绑定机制
  2. bilibili封面提取
  3. 江宁地区吃喝玩乐全攻略!
  4. ASP.NET2.0 ReportingServices,报表灵魂的收割者
  5. 三星堆的青铜机器人_三星堆“青铜大立人”,手里原来握的是什么东西,至今困扰考古界...
  6. android 指纹是否设置,检查Android是否支持指纹识别以及是否已经录入指纹
  7. egret 图文并排
  8. 区块链骇客第二讲: 自毁攻击
  9. 金蝶K3wise 演示版 W10安装
  10. 数据结构—第六章 图