背景:数据治理项目。

的功能是读取行业标准Word文档,生成Excel文档,然后加工Excel文档,加入领域等字段,表现形式为Column对应数据库表的Field字段,为后面生成建表sql语句做准备。

读取Excel生成Word是读取上面Excel,生成Word文档,汇报归档用。

Excel文档结构,第一个sheet是所有表汇总,然后每格表有个sheet,sheetName为表的中文说明(非实际表名,因为不同的领域的表有同名情况),sheet里面是具体的Field信息

  • 读取Excel

首先定义三个内部类接收Excel表的数据

// TableCategory:表类别。因为业务上会用到两套领域编码,所以定义了两个domain属性 @Setter @Getter public class TableCategory { private String domain; private String domain2; List tables; public void addTable(Table table) if (tables == null) { tables = new ArrayList<>(); } tables.add(table); } }


//Table:表。因为Excel的sheet名称不能包含冒号,*号,做替换 @Getter @Setter public class Table { private String category; private String name; private String enName; 。。。。 // 其他属性 private List fields; public String getName() { if (name == null) { return ""; } String str = name.trim().replace(":", "·").replace(":", "·"); str = str.replaceAll("\*", ""); return str; } public void addField(Field field) { if (fields == null) { fields = new ArrayList<>(); } fields.add(field); } }

// Field:列 @Getter @Setter public class Field { private String name; //源字段名 private String type; //字段类型及长度 。。。。 // 其他属性 }

读取Excel的内容按套路一行一行,一列一列读,然后赋值。

项目时间紧,要和客户汇报,数据组有些表还没有归并到Excel,有些还没拆成每表一个sheet的结构;针对每种情况单独做一个解析,解析后的内容都是按照上面三个类来接收处理。除了繁琐点,也都顺利。

后面还有一种场景就是数据组为了赶时间在生成的Word上直接修改Field内容,同时另外的同事又在Excel里面修改了领域的属性,需要合并Excel的领域属性+Word文档的Field内容。因为有前面的Word转Excel的代码,复用解决。

  • 输出Word文档

// 读取模版的style,用里面的项目编号的样式 FileInputStream fis = new FileInputStream("d:/template.docx"); XWPFDocument template = new XWPFDocument(fis); CTStyles templateStyles = template.getStyle(); XWPFDocument document = new XWPFDocument(); XWPFStyles newStyels = document.createStyles(); newStyels.setStyles(templateStyles); for (TableCategory category : tableCategories) { paragraph = document.createParagraph(); paragraph.setStyle("2"/*debug 看一下模版文档的style*/); run = paragraph.createRun(); if (idx == 0) { //两套领域 run.setText(category.domain + "域"); } else { run.setText(category.domain2 + "域"); } for (Table tableData : category.getTables()) { paragraph = document.createParagraph(); paragraph.setStyle("3"/*debug 看一下模版文档的style*/); run = paragraph.createRun(); run.setText(tableData.name + "(" + tableData.getEnName() + ")"); table = document.createTable(); // 遍历 tableData的fields, // 创建行createRow(); // 创建列createCell(); } } //执行output输出到Word文档

最近的工作内容,公司的代码不能全部粘贴,记录下关键步骤。

数据结构定义好了,TableCategory,Table,Field,虽然数据的来源会变,只需要开发不同的解析方法,最后输出到Word的代码不用动