Apache-POI导出Excel和Word

POM.XML配置POI相关jar包

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<!--poi-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>
poi</artifactId>
<version>3.10-beta2</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.10-beta2</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.10-beta2</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>3.0.2-FINAL</version>
</dependency>

编写相关工具类

可以自己写或用别人写好的轮子。Excel一般会比较简单实现,我在熟悉POI相关编写时先找了一个不错的开源代码,强烈推荐直接使用或作为学习参照:

https://github.com/hyberbin/J-Excel

Excel

需求:

  1. 根据需求编写对应实体类或存储结构等(省略)。

  2. 控制层:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
//导出Excel
@RequestMapping(value = "/exportExcel")
public ResponseEntity<Resource> exportExcel (@ModelAttribute("schoolYear") int schoolYear,
@ModelAttribute("schoolTerm") int semester,
@RequestParam("natualYear") String natureYear,
@RequestParam("natualMonth") String natureMonth){
try {
logger.info("/export/exportExcelForFdjx is running");
if(natureYear.isEmpty() && natureMonth.isEmpty()){
String[] strings = CommonUtil.getCurrentYearAndMonth();
natureYear = strings[0];
natureMonth = strings[1];
}
String fileName = schoolYear + "-学年-" + semester + "-学期-" + "绩效.xls";
ByteArrayOutputStream baos = exportService.exportExcel (schoolYear,semester,Integer.valueOf(natureYear),Integer.valueOf(natureMonth));
HttpHeaders headers = new HttpHeaders();
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
headers.add("charset", "utf-8");
fileName = URLEncoder.encode(fileName,"UTF-8");
headers.add("Content-Disposition", "attachment;fileName=\"" + fileName + "\"");
Resource resource = new InputStreamResource(new ByteArrayInputStream(baos.toByteArray()));
return ResponseEntity.ok().headers(headers).contentType(MediaType.parseMediaType("application/OCTET-STREAM")).body(resource);
}catch (Exception ex){
ex.printStackTrace();
logger.warning(ex.toString());
return ResponseEntity.notFound().eTag(ex.toString()).build();
}
}
  1. 服务层:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
public ByteArrayOutputStream exportExcel(
int schoolYear,int semester,int natureYear,int natureMonth)throws Exception{
ByteArrayOutputStream baos;
//数据准备,从持久层获取数据,核算等等

//组合标题,从数据结构中取出标题数据(非固定列数)
String[] rowName = new String[${总列数}];
rowName[0] = "序号";
rowName[1] = "列名A";
rowName[2] = "列名B";
rowName[3] = "列名C";
for(int i = 0;i < theoryHours.length;i++){//0-7 4-11 列名1~1.3
rowName[i+4] = theoryHourParms.get(i)+"";
}
rowName[theoryHours.length+4] = "0.8";
for(int i = 0;i < experimentParmList.size();i++){//0.6~0.7
rowName[i+theoryHours.length+5] = experimentParmList.get(i).getPositionRatio()+"";
}
rowName[theoryHours.length + experimentHours.length + 5] = "列名H";
rowName[theoryHours.length + experimentHours.length + 6] = "列名I";
rowName[theoryHours.length + experimentHours.length + 7] = "列名J";
rowName[theoryHours.length + experimentHours.length + 8] = "列名K";
rowName[theoryHours.length + experimentHours.length + 9] = "列名L";
rowName[theoryHours.length + experimentHours.length + 10] = "列名M";
//表格数据用dataList存储
List<Object[]> dataList = new ArrayList<Object[]>();
Object[] objs = null;
for(int i = 0; i < performances.size(); i++){
objs = new Object[rowName.length];
FloatingPerformance object = performances.get(i);
objs[0] = i;
objs[1] = object.getTeacherId();
objs[2] = object.getTeacherName();
objs[3] = object.getDepartmentName();
for(int j = 0;j < theoryHours.length;j++){
objs[j+4] = object.getTheoryHours().get(j).getHours()+"";
}
objs[theoryHours.length+4] = object.getXzytHours().getHours();
for(int j = 0;j < experimentHours.length;j++){
objs[j+theoryHours.length+5] = object.getExperimentHours().get(j).getHours()+"";
}
objs[theoryHours.length + experimentHours.length + 5] = object.getPayStandard();
objs[theoryHours.length + experimentHours.length + 6] = object.getHoursPay();
objs[theoryHours.length + experimentHours.length + 7] = object.getMonthAvePay();
objs[theoryHours.length + experimentHours.length + 8] = object.getOtherSubsidy();
objs[theoryHours.length + experimentHours.length + 9] = object.getFine();
objs[theoryHours.length + experimentHours.length + 10] = object.getRealAmount();
dataList.add(objs);
}
//生成合并单元格的标题
Map<Integer,int[]> rowMergeList = new HashMap<>();//横向合并的集合
Map<Integer,int[]> cellMergeList = new HashMap<>();//纵向合并的集合
int titleHeight = 2;
//第一行
int[] list0 = {4,theoryHours.length+3,theoryHours.length+5,theoryHours.length + experimentHours.length + 4};
int[] list1 = {5,theoryHours.length+3,theoryHours.length+5,theoryHours.length + experimentHours.length + 4};
int[] cell0 = {0,2};
int[] cell1 = {0,1};
List<String[]> mergeTitles = new ArrayList<>();
String[] mergeTitle0 = {"序号","列名A","列名B","列名C","列名N ","","","","","","","列名F","列名O","","列名H","列名I","列名J","列名K","列名L","列名M"};
String[] mergeTitle1 = {"序号","列名A","列名B","列名C","列名D","列名E","","","","","","列名F","列名G","","列名H","列名I","列名J","列名K","列名L","列名M"};
mergeTitles.add(mergeTitle0);
mergeTitles.add(mergeTitle1);
rowMergeList.put(0,list0);
rowMergeList.put(1,list1);
cellMergeList.put(0,cell0);
cellMergeList.put(1,cell0);
cellMergeList.put(2,cell0);
cellMergeList.put(3,cell0);
cellMergeList.put(theoryHours.length+4,cell1);
cellMergeList.put(theoryHours.length + experimentHours.length + 5,cell0);
cellMergeList.put(theoryHours.length + experimentHours.length + 6,cell0);
cellMergeList.put(theoryHours.length + experimentHours.length + 7,cell0);
cellMergeList.put(theoryHours.length + experimentHours.length + 8,cell0);
cellMergeList.put(theoryHours.length + experimentHours.length + 9,cell0);
cellMergeList.put(theoryHours.length + experimentHours.length + 10,cell0);
ExcelUtil excelUtil = new ExcelUtil("绩效",rowName,dataList,rowMergeList,cellMergeList,titleHeight,mergeTitles);
HSSFWorkbook workbook = excelUtil.export();
OutputStream outputStream = new ByteArrayOutputStream();
workbook.write(outputStream);

//输出流到浏览器
baos = (ByteArrayOutputStream) outputStream;
this.close(outputStream);
return baos;
}
  1. Excel工具类:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    public class ExcelUtil {
    private String title;//导出表的标题
    private String[] rowName;//导出表的列名
    private List<Object[]> dataList = new ArrayList<>();
    private Map<Integer,int[]> rowMergeList;//横向合并的集合
    private Map<Integer,int[]> cellMergeList;//纵向合并的集合
    private List<String[]> mergeTitles;//合并后的标题
    private int titleHeight;//标题栏高度(除了最底层标题)


    //构造方法,传入要导出的数据
    public ExcelUtil(String title, String[] rowName, List<Object[]> dataList,
    Map<Integer,int[]> rowMergeList,Map<Integer,int[]> cellMergeList,int titleHeight,List<String[]> mergeTitles){
    this.dataList = dataList;
    this.rowName = rowName;
    this.title = title;
    this.rowMergeList = rowMergeList;
    this.cellMergeList = cellMergeList;
    this.titleHeight = titleHeight;
    this.mergeTitles = mergeTitles;
    }

    /*
    * 导出数据
    * */
    public HSSFWorkbook export() throws Exception {
    HSSFWorkbook workbook = new HSSFWorkbook();//创建工作簿
    HSSFSheet sheet = workbook.createSheet(title);//创建工作表
    HSSFRow rowTitle = sheet.createRow(0);//表格标题行
    HSSFCell cellTitle = rowTitle.createCell(0);

    //sheet样式定义
    HSSFCellStyle columnTopStyle = this.getColumnTopStyle(workbook);//获取列头样式对象
    HSSFCellStyle style = this.getStyle(workbook);

    //生成表格大标题
    sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, (rowName.length-1)));
    cellTitle.setCellStyle(columnTopStyle);
    cellTitle.setCellValue(title);

    //生成合并的多层标题
    for(int n = 0;n < titleHeight;n++){
    HSSFRow rowDetailTitle = sheet.createRow( n+2);
    for(int m=0;m<rowName.length;m++){
    HSSFCell cellDetailTitle = rowDetailTitle.createCell(m); //创建列头对应个数的单元格
    }
    }

    // 定义所需列数
    int columnNum = rowName.length;
    HSSFRow rowRowName = sheet.createRow(2 + titleHeight);// 在索引2的位置创建行(最顶端的行开始的第二行)

    // 将列头设置到sheet的单元格中
    for(int n=0;n<columnNum;n++){
    HSSFCell cellRowName = rowRowName.createCell(n); //创建列头对应个数的单元格
    cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING); //设置列头单元格的数据类型
    HSSFRichTextString text = new HSSFRichTextString(rowName[n]);
    cellRowName.setCellValue(text); //设置列头单元格的值
    cellRowName.setCellStyle(columnTopStyle); //设置列头单元格样式
    }

    //开始合并标题
    if(rowMergeList.entrySet().size() > 0){
    for(Map.Entry<Integer,int[]> entry : rowMergeList.entrySet()){
    for(int i = 0;i < entry.getValue().length;i+=2)
    sheet.addMergedRegion(new CellRangeAddress(entry.getKey()+2,entry.getKey()+2, entry.getValue()[i], entry.getValue()[i+1]));
    }
    }
    if(cellMergeList.entrySet().size() > 0)
    for (Map.Entry<Integer,int[]> entry : cellMergeList.entrySet())
    sheet.addMergedRegion(new CellRangeAddress(
    entry.getValue()[0]+2,entry.getValue()[1]+2, entry.getKey(), entry.getKey()));
    //将合并后标题写入
    for(int i = 0;i < mergeTitles.size();i++){
    HSSFRow row = sheet.getRow(2+i);
    for(int j = 0;j < mergeTitles.get(i).length;j++){
    HSSFCell cellRowName = row.getCell(j);
    cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING); //设置列头单元格的数据类型
    HSSFRichTextString text = new HSSFRichTextString(mergeTitles.get(i)[j]);
    cellRowName.setCellValue(text); //设置列头单元格的值
    cellRowName.setCellStyle(columnTopStyle); //设置列头单元格样式
    }
    }

    //将查询出的数据设置到sheet对应的单元格中
    for(int i = 0;i < dataList.size();i++){
    Object[] obj = dataList.get(i);//遍历每个对象
    HSSFRow row = sheet.createRow(i + 3 + titleHeight);//创建所需的行数
    for(int j = 0; j < obj.length; j++){
    HSSFCell cell = null; //设置单元格的数据类型
    if(j == 0){
    cell = row.createCell(j,HSSFCell.CELL_TYPE_NUMERIC);
    cell.setCellValue(i+1);
    }else{
    cell = row.createCell(j,HSSFCell.CELL_TYPE_STRING);
    if(!"".equals(obj[j]) && obj[j] != null){
    cell.setCellValue(obj[j].toString()); //设置单元格的值
    }
    }
    cell.setCellStyle(style); //设置单元格样式
    }
    }

    //让列宽随着导出的列长自动适应
    for (int colNum = 0; colNum < columnNum; colNum++) {
    int columnWidth = sheet.getColumnWidth(colNum) / 256;
    for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) {
    HSSFRow currentRow;
    //当前行未被使用过
    if (sheet.getRow(rowNum) == null) {
    currentRow = sheet.createRow(rowNum);
    } else {
    currentRow = sheet.getRow(rowNum);
    }
    if (currentRow.getCell(colNum) != null) {
    HSSFCell currentCell = currentRow.getCell(colNum);
    if (currentCell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
    int length = currentCell.getRichStringCellValue() != null?currentCell.getStringCellValue().getBytes().length:columnWidth;
    if (columnWidth < length) {
    columnWidth = length;
    }
    }
    }
    }
    if(colNum == 0){
    sheet.setColumnWidth(colNum, (columnWidth-2) * 256);
    }else{
    sheet.setColumnWidth(colNum, (columnWidth+4) * 256);
    }
    }
    return workbook;
    }

    /*
    * 列头单元格样式
    */
    private HSSFCellStyle getColumnTopStyle(HSSFWorkbook workbook) {

    // 设置字体
    HSSFFont font = workbook.createFont();
    //设置字体大小
    font.setFontHeightInPoints((short)11);
    //字体加粗
    font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
    //设置字体名字
    font.setFontName("Courier New");
    //设置样式;
    HSSFCellStyle style = workbook.createCellStyle();
    //设置底边框;
    style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
    //设置底边框颜色;
    style.setBottomBorderColor(HSSFColor.BLACK.index);
    //设置左边框;
    style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
    //设置左边框颜色;
    style.setLeftBorderColor(HSSFColor.BLACK.index);
    //设置右边框;
    style.setBorderRight(HSSFCellStyle.BORDER_THIN);
    //设置右边框颜色;
    style.setRightBorderColor(HSSFColor.BLACK.index);
    //设置顶边框;
    style.setBorderTop(HSSFCellStyle.BORDER_THIN);
    //设置顶边框颜色;
    style.setTopBorderColor(HSSFColor.BLACK.index);
    //在样式用应用设置的字体;
    style.setFont(font);
    //设置自动换行;
    style.setWrapText(false);
    //设置水平对齐的样式为居中对齐;
    style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
    //设置垂直对齐的样式为居中对齐;
    style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
    return style;
    }

    /*
    * 列数据信息单元格样式
    */
    private HSSFCellStyle getStyle(HSSFWorkbook workbook) {
    // 设置字体
    HSSFFont font = workbook.createFont();
    //设置字体大小
    //font.setFontHeightInPoints((short)10);
    //字体加粗
    //font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
    //设置字体名字
    font.setFontName("Courier New");
    //设置样式;
    HSSFCellStyle style = workbook.createCellStyle();
    //设置底边框;
    style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
    //设置底边框颜色;
    style.setBottomBorderColor(HSSFColor.BLACK.index);
    //设置左边框;
    style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
    //设置左边框颜色;
    style.setLeftBorderColor(HSSFColor.BLACK.index);
    //设置右边框;
    style.setBorderRight(HSSFCellStyle.BORDER_THIN);
    //设置右边框颜色;
    style.setRightBorderColor(HSSFColor.BLACK.index);
    //设置顶边框;
    style.setBorderTop(HSSFCellStyle.BORDER_THIN);
    //设置顶边框颜色;
    style.setTopBorderColor(HSSFColor.BLACK.index);
    //在样式用应用设置的字体;
    style.setFont(font);
    //设置自动换行;
    style.setWrapText(false);
    //设置水平对齐的样式为居中对齐;
    style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
    //设置垂直对齐的样式为居中对齐;
    style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

    return style;
    }
    }

Word

需求:

通过 https://github.com/hyberbin/J-Excel 的开源工具代码来实现
或自编Word工具类实现

  1. 编写实体类和控制层,和Excel导出大体相同。

  2. 服务层

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
//导出数据
public OutputStream exportProgressTable(String mainCourseClassId,String classId,String courseId)throws Exception{
logger.info("初始化导出工具");
//初始化导出工具
WordUtil wordUtil = new WordUtil(WORD_TEMPLATE);
wordUtil.init();

//数据准备
ClassInfo classInfo = courseClassInfoRepository.findClassInfoById(classId);
List<BigDecimal> courseClassIds = courseClassInfoRepository.findAllCourseClassForClass(classId,courseId);
List<String> courseClassIdStrings = new ArrayList<>();
for(BigDecimal bigDecimal : courseClassIds)
courseClassIdStrings.add(bigDecimal.toString());
/******1.标题数据******/
ProgressInfo progressInfo = progressInfoRepository.findByMainCourseClassId(mainCourseClassId);
List<Map<String, String>> mapListTable = new ArrayList<>();
Map<String,Object> mapHeader = new HashMap<>();
if(progressInfo != null){
logger.info("表头数据非空");
/******2. 头表数据******/
mapHeader = progressInfo.toMap();
mapHeader.put("className",classInfo.getClassName());
mapHeader.put("major",classInfo.getMajor());
mapHeader.put("grade",classInfo.getGrade());
mapHeader.remove("experimentDiv");
mapHeader.put("experimentDiv",
(Integer.parseInt(progressInfo.getExperimentNumPerClass()) / Integer.parseInt(progressInfo.getExperimentNumPerGroup())) + "");
/******3. 表格:进度表******/
List<ProgressItem> items = progressItemRepository.findAllByProgressInfoIdAndCourseClassIdIn(
progressInfo.getProgressInfoId(),courseClassIdStrings);
if(items.size() > 0){
logger.info("表内非空");
mapListTable = loopToOneTableRowString(items,"planDate");
//处理节次,星期几,课时,教师
for(Map<String, String> map : mapListTable){
//节次
String classJc = String.valueOf(map.get("beginJc")) + "-" + String.valueOf(map.get("endJc")) + "节";
map.put("classJc",classJc);
//星期几
map.put("weekDayS",CommonUtil.weekDayToZNString(map.get("weekDay")));
if(map.get("isTheory").equals(IS_THEORY)){//理论课
map.put("tTeachHours",map.get("teachHours"));//理论课时
map.put("eTeachHours",map.get(""));//实验课时
map.put("jTeachHours",map.get(""));//见习课时
map.put("tTeachTeacherNames",map.get("teachTeacherNames"));//任课教师
map.put("eTeachTeacherNames",map.get(""));//实验教师
}else if(map.get("isTheory").equals(IS_EXPERIMENT)){//实验课
map.put("tTeachHours",map.get(""));//理论课时
map.put("eTeachHours",map.get("teachHours"));//实验课时
map.put("jTeachHours",map.get(""));//见习课时
map.put("tTeachTeacherNames",map.get(""));//任课教师
map.put("eTeachTeacherNames",map.get("teachTeacherNames"));//实验教师
}
}
}
}
wordUtil.export(mapHeader);
wordUtil.export(mapHeader,0);
wordUtil.export(mapListTable,1);
logger.info("生成Word");
return wordUtil.generate();
}

/**
* 获取数组数据,截断时间
* @param list
* @param fieldName
* @return
*/
private List<Map<String, Object>> loopToOneTableRow(List list,String fieldName){
List<Map<String, Object>> mapListTable = new ArrayList<>();
mapListTable = getMapListFromListPO(list);
//截断时间
for(Map<String, Object> map : mapListTable){
//时间
String dateString = CommonUtil.TimestampToDateString(Timestamp.valueOf(String.valueOf(map.get(fieldName))));
map.put(fieldName,dateString);//替换之前的数据
}
return mapListTable;
}

private List<Map<String, String>> loopToOneTableRowString(List list,String fieldName){
List<Map<String, String>> mapListTable = new ArrayList<>();
mapListTable = getMapListStringFromListPO(list);
//截断时间
for(Map<String, String> map : mapListTable){
//时间
String dateString = CommonUtil.TimestampToDateString(Timestamp.valueOf(String.valueOf(map.get(fieldName))));
map.put(fieldName,dateString);//替换之前的数据
}
return mapListTable;
}

/**
* 将PO数组转换为HashMap存储的键值对
* @param list
* @return
*/
private List<Map<String, Object>> getMapListFromListPO(List list){
//获取PO属性列名
String[] filedNames = getFiledName(list.get(0));
//将数组中每个PO属性列存储到HashMap中
List<Map<String, Object>> mapList = new ArrayList<>();
for(int i = 0;i < list.size();i++){
Map<String, Object> mapTemp = new HashMap<>();
for(int j = 0;j < filedNames.length;j++){
mapTemp.put(filedNames[j],getFieldStringValueByName(filedNames[j],list.get(i)));
}
mapList.add(mapTemp);
}
return mapList;
}

/**
* 将PO数组转换为HashMap存储的键值对
* @param list
* @return
*/
private List<Map<String, String>> getMapListStringFromListPO(List list){
//获取PO属性列名
String[] filedNames = getFiledName(list.get(0));
//将数组中每个PO属性列存储到HashMap中
List<Map<String, String>> mapList = new ArrayList<>();
for(int i = 0;i < list.size();i++){
Map<String, String> mapTemp = new HashMap<>();
for(int j = 0;j < filedNames.length;j++){
mapTemp.put(filedNames[j],getFieldStringValueByName(filedNames[j],list.get(i)));
}
mapList.add(mapTemp);
}
return mapList;
}

/**
* 获取属性名数组
* */
private String[] getFiledName(Object o){
Field[] fields=o.getClass().getDeclaredFields();
String[] fieldNames=new String[fields.length];
for(int i=0;i<fields.length;i++){
fieldNames[i]=fields[i].getName();
}
return fieldNames;
}

/**
* 根据属性名获取属性值
* */
private String getFieldStringValueByName(String fieldName, Object o) {
try {
String firstLetter = fieldName.substring(0, 1).toUpperCase();
String getter = "get" + firstLetter + fieldName.substring(1);
Method method = o.getClass().getMethod(getter, new Class[] {});
Object value = method.invoke(o, new Object[] {});
return String.valueOf(value);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
  1. 工具类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
public class WordUtil {
private Logger logger = Logger.getLogger(WordUtil.class);
//模板路径
private String templatePath;
//doc文件
private CustomXWPFDocument document = null;
//文件读入流
private FileInputStream inputStream = null;
//输出流
private OutputStream outputStream = null;

public WordUtil(String templatePath) {
this.templatePath = templatePath;
}

/**
* 初始化,将文件转换为XWPFDocument对象
* @throws IOException
*/
public void init() throws IOException{
inputStream = new FileInputStream(ResourceUtils.getFile(templatePath));
document = new CustomXWPFDocument(inputStream);
}

/**
* 替换占位符
* @param params
* @return
* @throws Exception
*/
public boolean export(Map<String,Object> params) throws Exception{
this.replaceInPara(document, params);
return true;
}

/**
* 替换表格中的占位符
* @param params
* @param tableIndex
* @return
* @throws Exception
*/
public boolean export(Map<String,Object> params,int tableIndex) throws Exception{
this.replaceInTable(document, params,tableIndex);
return true;
}

/**
* 循环生成表格
* @param params
* @param tableIndex
* @return
* @throws Exception
*/
public boolean export(List<Map<String, String>> params, int tableIndex) throws Exception{
return export(params,tableIndex,false);
}

public boolean export(List<Map<String, String>> params, int tableIndex,boolean hasTotalRow) throws Exception{
this.insertValueToTable(document, params, tableIndex,hasTotalRow);
return true;
}

/**
* 循环生成多表
* @param params
* @param tableIndex
* @param ifPageBreak
* @return
* @throws Exception
*/
public boolean exportTableList(List<Map<String, Object>> params, int tableIndex,String title,boolean ifPageBreak) throws Exception{
this.createListToTables(document,params,tableIndex,title,ifPageBreak);
return true;
}

/**
* 导出图片
* @param params
* @return
* @throws Exception
*/
public boolean exportImg(Map<String,Object> params) throws Exception{
List<XWPFTable> list = document.getTables();
System.out.println(list.size());
return true;
}

/**
* 生成word文档
* @return
* @throws IOException
*/
public OutputStream generate() throws IOException{
// outputStream = new FileOutputStream(outDocPath);
// document.write(outputStream);
// this.close(outputStream);
// this.close(inputStream);
// return true;
outputStream = new ByteArrayOutputStream();
document.write(outputStream);
this.close(outputStream);
this.close(inputStream);
return outputStream;
}

/**
* 根据数组元素个数生成表个数
* @param doc
* @param list
* @param tableIndex
*/
private void createListToTables(XWPFDocument doc,List<Map<String, Object>> list,int tableIndex,String title,boolean ifPageBreak)throws Exception{
// 有一个模板文件后, 要生成多份表格, 很自然的一个想法是在这个文件里复制多份这个表格.
// 但是这在POI中是行不通的, 你可以复制, 但小到段落大到表格, 复制出来的东西和原来的都储存在同一块堆内存上,
// 当你试图写入的时候, 表面上是通过栈内存中的不同引用而选中了不同的表格,
// 但这个引用之后指向的堆内存却是一样的, 其本质上是同一个东西
// 因此就出现了这样的现象: 复制了很多表, 但后面的表是空的, 所有的东西都在第一张表里.

//解决办法:生成临时模板, 转存一下, 再次打开后才写入内容

//获取模板中的所有表和所有段落
List<XWPFTable> tableList = doc.getTables();
if(tableList.size()<=tableIndex){
throw new Exception("tableIndex对应的表格不存在");
}
//获取要插入数据的表
XWPFTable template = tableList.get(tableIndex);
//根据数组大小生成对应数量的表,注意模板表已有,要先插入数据再复制表
for(int i = 1;i < list.size();i++){
//获取表格位置游标
XmlCursor xmlCursor = doc.getDocument().getBody().getTblArray(tableIndex).newCursor();
//表之间没有段落则会成为一个表,所以要在两表间插入一个新的段落
//先在表格前面生成一个空段落
XWPFParagraph newP = doc.insertNewParagraph(xmlCursor);
//设置分页或分隔
if(ifPageBreak){
newP.setPageBreak(true);
}else{
newP.setBorderBottom(Borders.NONE);
}
//获取段落的游标
XmlCursor newCursor = newP.getCTP().newCursor();
//在游标位置插入新表
doc.insertNewTbl(newCursor);
//将新表用模板替换
doc.setTable(tableIndex,template);
}
//先生成临时模板
generateFakeForTable(list,tableIndex,title,ifPageBreak);
}

/**
* 通过字节输出流转存Word模板,将模板作为读入流再对其中的表进行插入数据
* @return
* @throws IOException
*/
public void generateFakeForTable(List<Map<String, Object>> list,int tableIndex,String title,boolean ifPageBreak) throws IOException{
try {
logger.info("------------------generateFakeForTable------------------");
//新建输出流,暂存生成的word模板
ByteArrayOutputStream baos = new ByteArrayOutputStream();
//写出word到输出流
document.write(baos);
//将输出流当作模板读入
ByteArrayInputStream swapStream = new ByteArrayInputStream(baos.toByteArray());
//要重置读入文件
document = new CustomXWPFDocument(swapStream);
//插入标题,不分页则不加
if(ifPageBreak && list.size() > 1){
for(int i = 1;i < list.size();i++){
writeTableTitle(document,title,tableIndex+i);
}
}
//循环插入数据
insertListToTables(document,list,tableIndex);
}catch (Exception ex){
ex.printStackTrace();
}
}

/**
* 多表循环插入数据
* @param doc
* @param list
* @param tableIndex
* @throws Exception
*/
private void insertListToTables(XWPFDocument doc,List<Map<String, Object>> list,int tableIndex)throws Exception{
//依次插入数据到表中
for(int i = 0;i < list.size();i++){
Map<String, Object> params = list.get(i);
replaceInTable(doc,params,tableIndex+i);
}
}

/**
* 为表格添加标题
* @param doc
* @param title
* @param tableIndex
* @throws Exception
*/
private void writeTableTitle(XWPFDocument doc,String title,int tableIndex)throws Exception{
//获取表格位置游标
XmlCursor xmlCursor = doc.getDocument().getBody().getTblArray(tableIndex).newCursor();
//表之间没有段落则会成为一个表,所以要在两表间插入一个新的段落
//先在表格前面生成一个空段落
XWPFParagraph newP = doc.insertNewParagraph(xmlCursor);
//设置居中
newP.setAlignment(ParagraphAlignment.CENTER);
//XWPFRun代表有相同属性的一块区域
XWPFRun run = newP.createRun();
//加入标题
run.setText(title);
run.setBold(true);
run.setFontSize(16);
}


/**
* 替换表格中的变量
* @param doc
* @param params
* @param tableIndex
* @throws Exception
*/
private void replaceInTable(XWPFDocument doc, Map<String, Object> params,int tableIndex) throws Exception {
List<XWPFTable> tableList = doc.getTables();
if(tableList.size() <= tableIndex){
throw new Exception("tableIndex对应的表格不存在");
}else {
XWPFTable table = tableList.get(tableIndex);
List<XWPFTableRow> rows;
List<XWPFTableCell> cells;
List<XWPFParagraph> paras;
rows = table.getRows();
//遍历表格替换变量
for(XWPFTableRow row : rows){
cells = row.getTableCells();
for(XWPFTableCell cell : cells){
paras = cell.getParagraphs();
for (XWPFParagraph para : paras){
this.replaceInPara(para, params);
}
}
}
}
}

/**
* 替换段落中的变量
* @param doc
* @param params
* @throws Exception
*/
private void replaceInPara(XWPFDocument doc, Map<String, Object> params) throws Exception {
Iterator<XWPFParagraph> iterator = doc.getParagraphsIterator();
XWPFParagraph para;
while(iterator.hasNext()){
para = iterator.next();
this.replaceInPara(para,params);
}
}

/**
* 替换段落中的变量
* @param para
* @param params
* @throws Exception
*/
private boolean replaceInPara(XWPFParagraph para, Map<String, Object> params) throws Exception {
boolean data = false;
List<XWPFRun> runs;
//当有符合条件的占位符时
if (this.matcher(para.getParagraphText()).find()) {
runs = para.getRuns();
data = true;
Map<Integer,String> tempMap = new HashMap<Integer,String>();
for (int i = 0; i < runs.size(); i++) {
XWPFRun run = runs.get(i);
String runText = run.toString();
//以"$"开头
boolean begin = runText.contains("$");
boolean end = runText.contains("}");
if(begin && end){
tempMap.put(i, runText);
fillBlock(para, params, tempMap, i);
continue;
}else if(begin && !end){
tempMap.put(i, runText);
continue;
}else if(!begin && end){
tempMap.put(i, runText);
fillBlock(para, params, tempMap, i);
continue;
}else{
if(tempMap.size()>0){
tempMap.put(i, runText);
continue;
}
continue;
}
}
} else if (this.matcherRow(para.getParagraphText())) {
runs = para.getRuns();
data = true;
}
return data;
}

/**
* 填充run内容
* @param para
* @param params
* @param tempMap
* @param index
* @throws InvalidFormatException
* @throws IOException
* @throws Exception
*/
private void fillBlock(XWPFParagraph para, Map<String, Object> params, Map<Integer, String> tempMap, int index) throws InvalidFormatException, IOException, Exception {
Matcher matcher;
if(tempMap!=null&&tempMap.size()>0){
String wholeText = "";
List<Integer> tempIndexList = new ArrayList<Integer>();
for(Map.Entry<Integer, String> entry :tempMap.entrySet()){
tempIndexList.add(entry.getKey());
wholeText+=entry.getValue();
}
if(wholeText.equals("")){
return;
}
matcher = this.matcher(wholeText);
if (matcher.find()) {
boolean isPic = false;
int width = 0;
int height = 0;
int picType = 0;
String path = null;
String keyText = matcher.group().substring(2,matcher.group().length()-1);
Object value = params.get(keyText);
String newRunText = "";
String fileName = "";
if(value instanceof String){
newRunText = matcher.replaceFirst(String.valueOf(value));
}else if(value instanceof Map){//插入图片
logger.info("------------------keyText is " + keyText);
logger.info("------------------value instanceof Map");
isPic = true;
Map pic = (Map)value;
width = Integer.parseInt(pic.get("width").toString());
height = Integer.parseInt(pic.get("height").toString());
picType = getPictureType(pic.get("type").toString());
path = pic.get("path").toString();
fileName = pic.get("fileName").toString();
}
//模板样式
XWPFRun tempRun = null;
// 直接调用XWPFRun的setText()方法设置文本时,在底层会重新创建一个XWPFRun,把文本附加在当前文本后面,
// 所以我们不能直接设值,需要先删除当前run,然后再自己手动插入一个新的run。
for(Integer pos : tempIndexList){
tempRun = para.getRuns().get(pos);
tempRun.setText("", 0);
}
if(tempRun != null){
if(isPic){
logger.info("------------------isPic");
logger.info("------------------path is " + path);
//addPicture方法的最后两个参数必须用Units.toEMU转化一下
//para.insertNewRun(index).addPicture(getPicStream(path), picType, "测试",Units.toEMU(width), Units.toEMU(height));
//--此POI方法有BUG
//tempRun.addPicture(getPicStream(path), picType, path,Units.toEMU(width), Units.toEMU(height));
CTInline ctInline = tempRun.getCTR().addNewDrawing().addNewInline();//设置段落行
String id = document.addPictureData(getPicStream(path), picType);
int idPic = document.getAllPackagePictures().size()+1;
document.createPic(id,idPic,width,height,ctInline);//添加图片
//tempRun.setText(fileName);
//tempRun.addBreak(BreakType.COLUMN);
}else{
//样式继承
if(newRunText.contains("\n")){
String[] textArr = newRunText.split("\n");
if(textArr.length>0){
//设置字体信息
String fontFamily = tempRun.getFontFamily();
int fontSize = tempRun.getFontSize();
logger.info("------------------"+fontSize);
for(int i=0;i<textArr.length;i++){
if(i==0){
tempRun.setText(textArr[0],0);
}else{
if(StringUtils.isNotEmpty(textArr[i])){
XWPFRun newRun=para.createRun();
//设置新的run的字体信息
newRun.setFontFamily(fontFamily);
if(fontSize==-1)
newRun.setFontSize(10);
else
newRun.setFontSize(fontSize);
newRun.addBreak();
newRun.setText(textArr[i], 0);
}
}
}
}
}else
tempRun.setText(newRunText,0);
}
}
}
tempMap.clear();
}
}

/**
* Clone Object
* @param obj
* @return
* @throws Exception
*/
private Object cloneObject(Object obj) throws Exception{
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(byteOut);
out.writeObject(obj);
ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
ObjectInputStream in =new ObjectInputStream(byteIn);
return in.readObject();
}

/**
* 循环插入表格数据
* @param doc
* @param params
* @param tableIndex
* @throws Exception
*/
private void insertValueToTable(XWPFDocument doc,List<Map<String, String>> params,int tableIndex) throws Exception {
insertValueToTable(doc,params,tableIndex,false);
}

/**
* 循环插入表格数据
* @param doc
* @param params
* @param tableIndex
* @param hasTotalRow
* @throws Exception
*/
private void insertValueToTable(XWPFDocument doc,List<Map<String, String>> params,int tableIndex,Boolean hasTotalRow) throws Exception {
//获取模板中的所有表
List<XWPFTable> tableList = doc.getTables();
if(tableList.size()<=tableIndex){
throw new Exception("tableIndex对应的表格不存在");
}
//获取要插入数据的表
XWPFTable table = tableList.get(tableIndex);
//获取所有行
List<XWPFTableRow> rows = table.getRows();
if(rows.size()<2){
throw new Exception("tableIndex对应表格应该为2行");
}
//模板行
XWPFTableRow tmpRow = rows.get(1);
List<XWPFTableCell> tmpCells = null;
List<XWPFTableCell> cells = null;
XWPFTableCell tmpCell = null;

tmpCells = tmpRow.getTableCells();
String cellText = null;
String cellTextKey = null;
Map<String,Object> totalMap = null;

for (int i = 0, len = params.size(); i < len; i++) {
Map<String,String> map = params.get(i);
if(map.containsKey("total")){
totalMap = new HashMap<String,Object>();
totalMap.put("total", map.get("total"));
continue;
}
XWPFTableRow row = table.createRow();
row.setHeight(tmpRow.getHeight());
cells = row.getTableCells();
// 插入的行会填充与表格第一行相同的列数
for (int k = 0, klen = cells.size(); k < klen; k++) {
tmpCell = tmpCells.get(k);
XWPFTableCell cell = cells.get(k);
cellText = tmpCell.getText();
if(StringUtils.isNotBlank(cellText)){
//转换为mapkey对应的字段
cellTextKey = cellText.replace("$", "").replace("{", "").replace("}","");
if(map.containsKey(cellTextKey)){
setCellText(tmpCell, cell, map.get(cellTextKey));
}
}
}
}
// 删除模版行
table.removeRow(1);
if(hasTotalRow && totalMap!=null){
XWPFTableRow row = table.getRow(1);
//cell.setText("11111");
XWPFTableCell cell = row.getCell(0);
replaceInPara(cell.getParagraphs().get(0),totalMap);
/*String wholeText = cell.getText();
Matcher matcher = this.matcher(wholeText);
if(matcher.find()){*/
/*List<XWPFParagraph> paras = cell.getParagraphs();
for (XWPFParagraph para : paras) {
this.replaceInPara(para, totalMap);
}*/
//}
table.addRow(row);
table.removeRow(1);
}
}

private void setCellText(XWPFTableCell tmpCell, XWPFTableCell cell, String text) throws Exception {
CTTc cttc2 = tmpCell.getCTTc();
CTTcPr ctPr2 = cttc2.getTcPr();
CTTc cttc = cell.getCTTc();
CTTcPr ctPr = cttc.addNewTcPr();
//cell.setColor(tmpCell.getColor());
// cell.setVerticalAlignment(tmpCell.getVerticalAlignment());
if (ctPr2.getTcW() != null) {
ctPr.addNewTcW().setW(ctPr2.getTcW().getW());
}
if (ctPr2.getVAlign() != null) {
ctPr.addNewVAlign().setVal(ctPr2.getVAlign().getVal());
}
if (cttc2.getPList().size() > 0) {
CTP ctp = cttc2.getPList().get(0);
if (ctp.getPPr() != null) {
if (ctp.getPPr().getJc() != null) {
cttc.getPList().get(0).addNewPPr().addNewJc()
.setVal(ctp.getPPr().getJc().getVal());
}
}
}
if (ctPr2.getTcBorders() != null) {
ctPr.setTcBorders(ctPr2.getTcBorders());
}
XWPFParagraph tmpP = tmpCell.getParagraphs().get(0);
XWPFParagraph cellP = cell.getParagraphs().get(0);
XWPFRun tmpR = null;
if (tmpP.getRuns() != null && tmpP.getRuns().size() > 0) {
tmpR = tmpP.getRuns().get(0);
}
List<XWPFRun> runList = new ArrayList<XWPFRun>();
if(text==null){
XWPFRun cellR = cellP.createRun();
runList.add(cellR);
cellR.setText("");
}else{
//这里的处理思路是:$b认为是段落的分隔符,分隔后第一个段落认为是要加粗的
if(text.contains("\b")){//段落,加粗,主要用于产品行程
String[] bArr = text.split("\b");
for(int b=0;b<bArr.length;b++){
XWPFRun cellR = cellP.createRun();
runList.add(cellR);
if(b==0){//默认第一个段落加粗
cellR.setBold(true);
}
if(bArr[b].contains("\n")){
String[] arr = bArr[b].split("\n");
for(int i = 0; i < arr.length; i++){
if(i > 0){
cellR.addBreak();
}
cellR.setText(arr[i]);
}
}else{
cellR.setText(bArr[b]);
}
}
}else{
XWPFRun cellR = cellP.createRun();
runList.add(cellR);
if(text.contains("\n")){
String[] arr = text.split("\n");
for(int i = 0; i < arr.length; i++){
if(i > 0){
cellR.addBreak();
}
cellR.setText(arr[i]);
}
}else{
cellR.setText(text);
}
}
}

// 复制字体信息
if (tmpR != null) {
//cellR.setBold(tmpR.isBold());
//cellR.setBold(true);
for(XWPFRun cellR : runList){
if(!cellR.isBold())
cellR.setBold(tmpR.isBold());
cellR.setItalic(tmpR.isItalic());
cellR.setStrike(tmpR.isStrike());
cellR.setUnderline(tmpR.getUnderline());
cellR.setColor(tmpR.getColor());
cellR.setTextPosition(tmpR.getTextPosition());
if (tmpR.getFontSize() != -1)
cellR.setFontSize(tmpR.getFontSize());
if (tmpR.getFontFamily() != null)
cellR.setFontFamily(tmpR.getFontFamily());
if (tmpR.getCTR() != null) {
if (tmpR.getCTR().isSetRPr()) {
CTRPr tmpRPr = tmpR.getCTR().getRPr();
if (tmpRPr.isSetRFonts()) {
CTFonts tmpFonts = tmpRPr.getRFonts();
CTRPr cellRPr = cellR.getCTR().isSetRPr() ? cellR
.getCTR().getRPr() : cellR.getCTR().addNewRPr();
CTFonts cellFonts = cellRPr.isSetRFonts() ? cellRPr
.getRFonts() : cellRPr.addNewRFonts();
cellFonts.setAscii(tmpFonts.getAscii());
cellFonts.setAsciiTheme(tmpFonts.getAsciiTheme());
cellFonts.setCs(tmpFonts.getCs());
cellFonts.setCstheme(tmpFonts.getCstheme());
cellFonts.setEastAsia(tmpFonts.getEastAsia());
cellFonts.setEastAsiaTheme(tmpFonts.getEastAsiaTheme());
cellFonts.setHAnsi(tmpFonts.getHAnsi());
cellFonts.setHAnsiTheme(tmpFonts.getHAnsiTheme());
}
}
}
}
}
// 复制段落信息
cellP.setAlignment(tmpP.getAlignment());
cellP.setVerticalAlignment(tmpP.getVerticalAlignment());
cellP.setBorderBetween(tmpP.getBorderBetween());
cellP.setBorderBottom(tmpP.getBorderBottom());
cellP.setBorderLeft(tmpP.getBorderLeft());
cellP.setBorderRight(tmpP.getBorderRight());
cellP.setBorderTop(tmpP.getBorderTop());
cellP.setPageBreak(tmpP.isPageBreak());
if (tmpP.getCTP() != null) {
if (tmpP.getCTP().getPPr() != null) {
CTPPr tmpPPr = tmpP.getCTP().getPPr();
CTPPr cellPPr = cellP.getCTP().getPPr() != null ? cellP
.getCTP().getPPr() : cellP.getCTP().addNewPPr();
// 复制段落间距信息
CTSpacing tmpSpacing = tmpPPr.getSpacing();
if (tmpSpacing != null) {
CTSpacing cellSpacing = cellPPr.getSpacing() != null ? cellPPr
.getSpacing() : cellPPr.addNewSpacing();
if (tmpSpacing.getAfter() != null)
cellSpacing.setAfter(tmpSpacing.getAfter());
if (tmpSpacing.getAfterAutospacing() != null)
cellSpacing.setAfterAutospacing(tmpSpacing
.getAfterAutospacing());
if (tmpSpacing.getAfterLines() != null)
cellSpacing.setAfterLines(tmpSpacing.getAfterLines());
if (tmpSpacing.getBefore() != null)
cellSpacing.setBefore(tmpSpacing.getBefore());
if (tmpSpacing.getBeforeAutospacing() != null)
cellSpacing.setBeforeAutospacing(tmpSpacing.getBeforeAutospacing());
if (tmpSpacing.getBeforeLines() != null)
cellSpacing.setBeforeLines(tmpSpacing.getBeforeLines());
if (tmpSpacing.getLine() != null)
cellSpacing.setLine(tmpSpacing.getLine());
if (tmpSpacing.getLineRule() != null)
cellSpacing.setLineRule(tmpSpacing.getLineRule());
}
// 复制段落缩进信息
CTInd tmpInd = tmpPPr.getInd();
if (tmpInd != null) {
CTInd cellInd = cellPPr.getInd() != null ? cellPPr.getInd()
: cellPPr.addNewInd();
if (tmpInd.getFirstLine() != null)
cellInd.setFirstLine(tmpInd.getFirstLine());
if (tmpInd.getFirstLineChars() != null)
cellInd.setFirstLineChars(tmpInd.getFirstLineChars());
if (tmpInd.getHanging() != null)
cellInd.setHanging(tmpInd.getHanging());
if (tmpInd.getHangingChars() != null)
cellInd.setHangingChars(tmpInd.getHangingChars());
if (tmpInd.getLeft() != null)
cellInd.setLeft(tmpInd.getLeft());
if (tmpInd.getLeftChars() != null)
cellInd.setLeftChars(tmpInd.getLeftChars());
if (tmpInd.getRight() != null)
cellInd.setRight(tmpInd.getRight());
if (tmpInd.getRightChars() != null)
cellInd.setRightChars(tmpInd.getRightChars());
}
}
}
}

/**
* 删除表中的行
* @param tableAndRowsIdxMap 表的索引和行索引集合
*/
public void deleteRow(Map<Integer,List<Integer>> tableAndRowsIdxMap){
if(tableAndRowsIdxMap!=null && !tableAndRowsIdxMap.isEmpty()){
List<XWPFTable> tableList = document.getTables();
for(Map.Entry<Integer, List<Integer>> map : tableAndRowsIdxMap.entrySet()){
Integer tableIdx = map.getKey();
List<Integer> rowIdxList = map.getValue();
if(rowIdxList!=null && rowIdxList.size()>0){
if(tableList.size()<=tableIdx){
logger.error("表格"+tableIdx+"不存在");
continue;
}
XWPFTable table = tableList.get(tableIdx);
List<XWPFTableRow> rowList = table.getRows();
for(int i=rowList.size()-1;i>=0;i--){
if(rowIdxList.contains(i)){
table.removeRow(i);
}
}
}
}
}
}


/**
* 正则匹配字符串
* @param str
* @return
*/
private Matcher matcher(String str) {
Pattern pattern = Pattern.compile("\\$\\{(.+?)\\}",
Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(str);
return matcher;
}

/**
* 正则匹配字符串
* @param str
* @return
*/
private boolean matcherRow(String str) {
Pattern pattern = Pattern.compile("\\$\\[(.+?)\\]",
Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(str);
return matcher.find();
}

/**
* 根据图片类型,取得对应的图片类型代码
* @param picType
* @return int
*/
private int getPictureType(String picType){
int res = XWPFDocument.PICTURE_TYPE_PICT;
if(picType != null){
if(picType.equalsIgnoreCase("png")){
res = XWPFDocument.PICTURE_TYPE_PNG;
}else if(picType.equalsIgnoreCase("dib")){
res = XWPFDocument.PICTURE_TYPE_DIB;
}else if(picType.equalsIgnoreCase("emf")){
res = XWPFDocument.PICTURE_TYPE_EMF;
}else if(picType.equalsIgnoreCase("jpg") || picType.equalsIgnoreCase("jpeg")){
res = XWPFDocument.PICTURE_TYPE_JPEG;
}else if(picType.equalsIgnoreCase("wmf")){
res = XWPFDocument.PICTURE_TYPE_WMF;
}
}
return res;
}

private InputStream getPicStream(String picPath) throws Exception{
//判断是网络还是本地图片
if(picPath.contains(":/")){//本地获取
return new FileInputStream(picPath);
}else {//网络获取图片
URL url = new URL(picPath);
//打开链接
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
//设置请求方式为"GET"
conn.setRequestMethod("GET");
//超时响应时间为5秒
conn.setConnectTimeout(5 * 1000);
//通过输入流获取图片数据
return conn.getInputStream();
}
}

/**
* 关闭输入流
* @param is 输入流
*/
private void close(InputStream is) {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

/**
* 关闭输出流
* @param os 输出流
*/
private void close(OutputStream os) {
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

/**
* 保留小数点后两位
* @param d
* @return
*/
public static String getPoint2(Double d){
DecimalFormat df =new DecimalFormat("0.00");
return df.format(d);
}

public static void main(String[] args) {
/*BigDecimal b=new BigDecimal("56.244555");
System.out.println(":"+getPoint2(b.doubleValue()));*/
Integer b = new Integer(1);
Integer a = 1000;
Integer d = 1000;
int c = 1;
System.out.println(a==d);
}

/**
* 判断字符串是否都为数字
* @param str
* @return
*/
public static boolean isNumeric(String str){
Pattern pattern = Pattern.compile("[0-9]*");
Matcher isNum = pattern.matcher(str);
if( !isNum.matches() ){
return false;
}
return true;
}

/**
* 数字转换为汉语中人民币的大写
*/
public static class NumberToCN {
/**
* 汉语中数字大写
*/
private static final String[] CN_UPPER_NUMBER = { "零", "壹", "贰", "叁", "肆",
"伍", "陆", "柒", "捌", "玖" };

/**
* 汉语中货币单位大写,这样的设计类似于占位符
*/
private static final String[] CN_UPPER_MONETRAY_UNIT = { "分", "角", "元",
"拾", "佰", "仟", "万", "拾", "佰", "仟", "亿", "拾", "佰", "仟", "兆", "拾",
"佰", "仟" };

/**
* 特殊字符:整
*/
private static final String CN_FULL = "整";

/**
* 特殊字符:负
*/
private static final String CN_NEGATIVE = "负";

/**
* 金额的精度,默认值为2
*/
private static final int MONEY_PRECISION = 2;

/**
* 特殊字符:零元整
*/
private static final String CN_ZEOR_FULL = "零元" + CN_FULL;

/**
* 把输入的金额转换为汉语中人民币的大写
*
* @param numberOfMoney
* 输入的金额
* @return 对应的汉语大写
*/
public static String number2CNMontrayUnit(BigDecimal numberOfMoney) {
StringBuffer sb = new StringBuffer();
// -1, 0, or 1 as the value of this BigDecimal is negative, zero, or
// positive.
int signum = numberOfMoney.signum();
// 零元整的情况
if (signum == 0) {
return CN_ZEOR_FULL;
}
//这里会进行金额的四舍五入
long number = numberOfMoney.movePointRight(MONEY_PRECISION).setScale(0, 4).abs().longValue();
// 得到小数点后两位值
long scale = number % 100;
int numUnit = 0;
int numIndex = 0;
boolean getZero = false;
// 判断最后两位数,一共有四中情况:00 = 0, 01 = 1, 10, 11
if (!(scale > 0)) {
numIndex = 2;
number = number / 100;
getZero = true;
}
if ((scale > 0) && (!(scale % 10 > 0))) {
numIndex = 1;
number = number / 10;
getZero = true;
}
int zeroSize = 0;
while (true) {
if (number <= 0) {
break;
}
// 每次获取到最后一个数
numUnit = (int) (number % 10);
if (numUnit > 0) {
if ((numIndex == 9) && (zeroSize >= 3)) {
sb.insert(0, CN_UPPER_MONETRAY_UNIT[6]);
}
if ((numIndex == 13) && (zeroSize >= 3)) {
sb.insert(0, CN_UPPER_MONETRAY_UNIT[10]);
}
sb.insert(0, CN_UPPER_MONETRAY_UNIT[numIndex]);
sb.insert(0, CN_UPPER_NUMBER[numUnit]);
getZero = false;
zeroSize = 0;
} else {
++zeroSize;
if (!(getZero)) {
sb.insert(0, CN_UPPER_NUMBER[numUnit]);
}
if (numIndex == 2) {
if (number > 0) {
sb.insert(0, CN_UPPER_MONETRAY_UNIT[numIndex]);
}
} else if (((numIndex - 2) % 4 == 0) && (number % 1000 > 0)) {
sb.insert(0, CN_UPPER_MONETRAY_UNIT[numIndex]);
}
getZero = true;
}
// 让number每次都去掉最后一个数
number = number / 10;
++numIndex;
}
// 如果signum == -1,则说明输入的数字为负数,就在最前面追加特殊字符:负
if (signum == -1) {
sb.insert(0, CN_NEGATIVE);
}
// 输入的数字小数点后两位为"00"的情况,则要在最后追加特殊字符:整
if (!(scale > 0)) {
sb.append(CN_FULL);
}
return sb.toString();
}
}
}

后续

Word插入图片时,调用POI函数addPicture导致生成的Word无法打开。

public XWPFPicture addPicture(InputStream pictureData, int pictureType, String filename, int width, int height) throws InvalidFormatException, IOException

首先定位BUG产生原因应该是XWPFRun成员方法生成图片后无法在新版Word打开(xml问题?)

参考:https://blog.csdn.net/Alice_qixin/article/details/71730346

通过自实现Document继承XWPFDocument,实现插入图片方法createPic。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
public class CustomXWPFDocument extends XWPFDocument {
public CustomXWPFDocument(InputStream is) throws IOException {
super(is);
}

public void createPic(String blipId, int id, int width, int height, CTInline inline) {
final int EMU = 9525;
width *= EMU;
height *= EMU;
//String blipId = getAllPictures().get(id).getPackageRelationship().getId();
// CTInline inline = createParagraph().createRun().getCTR().addNewDrawing().addNewInline();
String picXml = "" +"<a:graphic xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\">" +
" <a:graphicData uri=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">" +
" <pic:pic xmlns:pic=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">" +
" <pic:nvPicPr>" +" <pic:cNvPr id=\"" + id + "\" name=\"Generated\"/>" +
" <pic:cNvPicPr/>" +
" </pic:nvPicPr>" +
" <pic:blipFill>" +
" <a:blip r:embed=\"" + blipId + "\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"/>" +
" <a:stretch>" +
" <a:fillRect/>" +
" </a:stretch>" +
" </pic:blipFill>" +
" <pic:spPr>" +
" <a:xfrm>" +
" <a:off x=\"0\" y=\"0\"/>" +
" <a:ext cx=\"" + width + "\" cy=\"" + height + "\"/>" +
" </a:xfrm>" +" <a:prstGeom prst=\"rect\">" +
" <a:avLst/>" +
" </a:prstGeom>" +
" </pic:spPr>" +
" </pic:pic>" +
" </a:graphicData>" +
"</a:graphic>";
//CTGraphicalObjectData graphicData = inline.addNewGraphic().addNewGraphicData();
XmlToken xmlToken = null;
try{
xmlToken = XmlToken.Factory.parse(picXml);
}catch(XmlException xe){
xe.printStackTrace();
}
inline.set(xmlToken);
//graphicData.set(xmlToken);
inline.setDistT(0);
inline.setDistB(0);
inline.setDistL(0);
inline.setDistR(0);
CTPositiveSize2D extent = inline.addNewExtent();
extent.setCx(width);extent.setCy(height);
CTNonVisualDrawingProps docPr = inline.addNewDocPr();
docPr.setId(id);
docPr.setName("Picture " + id);
docPr.setDescr("Generated");
}
}

用自定义的Document代替XWPFDocument,并在插入图片时参考写入以下代码

1
2
3
4
CTInline ctInline = tempRun.getCTR().addNewDrawing().addNewInline();//设置段落行
String id = document.addPictureData(getPicStream(path), picType);
int idPic = document.getAllPackagePictures().size()+1;
document.createPic(id,idPic,width,height,ctInline);//添加图片