导出Word工具类(根据数据动态生成并跨列)

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
package com.ksource.modules.common;
 
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.util.JSONTokener;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
 
/**
 * @author dxy
 *
 */
@Component
public class ExportWordUtil {
 
    public void createTable(String name, JSONArray json, HttpServletRequest request, HttpServletResponse response) throws Exception {
        XWPFDocument xdoc = new XWPFDocument();
        XWPFParagraph xp = xdoc.createParagraph();
        xp.setSpacingBefore(0);
        XWPFRun r = xp.createRun();
        r.setText(name+"查询信息");
        r.setFontFamily("宋体");
        r.setFontSize(18);
        r.setTextPosition(10);
        r.setBold(true);
        r.addBreak(); // 换行
        xp.setAlignment(ParagraphAlignment.CENTER);
 
        int sign = 0;
        for(int i = 0; i < json.size(); i++){
            JSONObject jsonObject = JSONObject.fromObject(json.get(i).toString());
            if ("1".equals(jsonObject.get("flag").toString())){
                sign = ++sign;
                xdoc.createParagraph();
                XWPFParagraph xp1 = xdoc.createParagraph();
                XWPFRun r1 = xp1.createRun();
                r1.setText((sign) +"."+ jsonObject.get("resourceName").toString());
                r1.setFontFamily("宋体");
                r1.setFontSize(16);
                r1.setBold(true);
                r1.setTextPosition(10);
                //r.addBreak(); // 换行
                xp1.setAlignment(ParagraphAlignment.LEFT);
                if (jsonObject.get("result") != null){
                    int index = 0;
                    JSONObject resultJsonObject = JSONObject.fromObject(jsonObject.get("result").toString());
                    for(Object key : resultJsonObject.keySet()){
                        String flag = parseJsonFormat(key.toString(),resultJsonObject.get(key).toString());
                        System.out.println(resultJsonObject.get(key).toString());
                        System.out.println(flag);
                        writeDoc(xdoc,(sign)+"."+(++index),key.toString(),resultJsonObject.get(key).toString(),flag);
                    }
                }
            }
        }
        downloadWord(xdoc,request,response);
    }
 
    private void writeDoc(XWPFDocument xdoc, String index, String key, String value, String flag){
        xdoc.createParagraph();
        XWPFParagraph xp = xdoc.createParagraph();
        XWPFRun r = xp.createRun();
        r.setText(index +"."+ key);
        r.setFontFamily("宋体");
        r.setFontSize(14);
        r.setBold(true);
        r.setTextPosition(10);
        //r.addBreak(); // 换行
        xp.setAlignment(ParagraphAlignment.LEFT);
        if("1".equals(flag)){
            getDetail(xdoc,value);
        }else if("2".equals(flag)){
            getList(xdoc,value);
        }else if("3".equals(flag)){
            getDetailList(xdoc,value);
        }
    }
 
    /**
     * 获取详情
     * @param xdoc
     * @param value
     */
    public void getDetail(XWPFDocument xdoc, String value){
        xdoc.createParagraph();
        int keyCount = 0;
        JSONObject valueJsonObject = JSONObject.fromObject(value);
        List list = new ArrayList();
        for(Object k : valueJsonObject.keySet()){
            ++keyCount;
            list.add(k.toString());
            list.add(valueJsonObject.get(k).toString());
        }
        int fromCellIndex = keyCount*2 % 6;
        Integer row_total_count = (keyCount*2%6 == 0) ? keyCount*2/6 : (keyCount*2/6 + 1);
        Integer col_total_count = 6; // 表格最多的列数
        if(keyCount * 2 < 6){
            col_total_count = keyCount * 2;
        }
        XWPFTable xTable = xdoc.createTable();
        CTTbl ttbl = xTable.getCTTbl();
        CTTblPr tblPr = ttbl.getTblPr() == null ? ttbl.addNewTblPr() : ttbl.getTblPr();
        CTTblWidth tblWidth = tblPr.isSetTblW() ? tblPr.getTblW() : tblPr.addNewTblW();
        tblWidth.setW(new BigInteger("9072"));
        tblWidth.setType(STTblWidth.DXA);
        for (int i = 0; i < row_total_count; i++) {
            XWPFTableRow row = xTable.insertNewTableRow(i);
            row.setHeight(450);
            int t = i*col_total_count;
            for (int j = 0; j < col_total_count; j++) {
                XWPFTableCell cell = row.createCell();
                XWPFParagraph p = cell.addParagraph();
                p.setAlignment(ParagraphAlignment.CENTER);
                p.setSpacingBefore(100);
                XWPFRun xRun = p.createRun();
                xRun.setFontSize(9);
                if ((j+t) < list.size()){
                    if(j % 2 == 0){
                        xRun.setBold(true);//是否粗体
                        cell.setColor("f0f7ff");
                    }
                    if(!"".equals(list.get(j+t).toString())){
                        xRun.setText(list.get(j+t).toString());
                    }else{
                        xRun.setText("暂无");
                    }
                }else if(i == row_total_count - 1 && j == col_total_count - 1){
                    mergeCellsHorizontal(xTable,row_total_count-1,col_total_count,fromCellIndex-1,col_total_count-1);
                }
            }
        }
        xTable.removeRow(row_total_count);
    }
 
    /**
     * 获取列表
     * @param xdoc
     * @param value
     */
    public void getList(XWPFDocument xdoc, String value){
        JSONArray valueJsonArray = JSONArray.fromObject(value);
        for (int i = 0; i < valueJsonArray.size(); i++){
            getDetail(xdoc,valueJsonArray.get(i).toString());
        }
    }
 
    /**
     * 获取详情和列表
     * @param xdoc
     * @param value
     */
    public void getDetailList(XWPFDocument xdoc, String value){
        JSONObject valueJsonObject = JSONObject.fromObject(value);
        for(Object k : valueJsonObject.keySet()){
            String flag = parseJsonFormat(k.toString(),valueJsonObject.get(k).toString());
            if("1".equals(flag)){
                getDetail(xdoc,valueJsonObject.get(k).toString());
            }else if("2".equals(flag)){
                getList(xdoc,valueJsonObject.get(k).toString());
            }
        }
    }
 
    /**
     * 判断json格式
     * @param key
     * @param value
     * @return
     */
    public String parseJsonFormat(String key, String value){
        //当flag=1时json格式为详情,当flag=2时json格式为列表,当flag=3时json格式为详情+列表
        String flag = "";
        Object json = new JSONTokener(value).nextValue();
        if(json instanceof JSONObject){
            JSONObject jsonObject = (JSONObject)json;
            for(Object k : jsonObject.keySet()){
                boolean isJSON = isJSON(jsonObject.get(k).toString());
                if(isJSON){
                    flag = "3";
                    break;
                }else{
                    flag = "1";
                }
            }
        }else if (json instanceof JSONArray){
            JSONArray jsonArray = (JSONArray)json;
            flag = "2";
        }
        return flag;
    }
 
    /**
     * 判断是否为json
     * @param str
     * @return
     */
    public boolean isJSON(String str) {
        boolean result = false;
        try {
            Object obj = JSONObject.fromObject(str);
            result = true;
        } catch (Exception e) {
            result=false;
        }
        return result;
    }
 
    /**
     * 设置表头内容
     * @param cell
     * @param text
     * @param bgcolor
     * @param width
     */
    private static void setCellText(XWPFDocument xdoc, XWPFTableCell cell,
                                    String text, String bgcolor, int width) {
        CTTc cttc = cell.getCTTc();
        CTTcPr cellPr = cttc.addNewTcPr();
        cellPr.addNewTcW().setW(BigInteger.valueOf(width));
        XWPFParagraph paragraph = cell.getParagraphs().get(0);
        paragraph.setAlignment(ParagraphAlignment.CENTER); //设置表头单元格居中
        XWPFRun run  = paragraph.createRun();
        run.setFontFamily("仿宋_GB2312");
        run.setFontSize(16); //设置表头单元格字号
        //run.setBold(true); //设置表头单元格加粗
        run.setText(text);
    }
 
    /**
     * 设置列宽
     *
     * @param index
     * @return
     */
    private static int getCellWidth(int index) {
        int cwidth = 1000;
        if (index == 0) {
            cwidth = 1000;
        } else if (index == 1) {
            cwidth = 2100;
        } else if (index == 2) {
            cwidth = 3200;
        } else if (index == 3) {
            cwidth = 2100;
        }
        return cwidth;
    }
 
    /**
     * 跨列合并
     * @param table
     * @param row    所合并的行
     * @param fromCell    起始列
     * @param toCell    终止列
     */
    public void mergeCellsHorizontal(XWPFTable table, int row, int colNum, int fromCell, int toCell) {
        table.getRow(row).getCell(fromCell).getCTTc().addNewTcPr().addNewTcW()
                .setW(BigInteger.valueOf((9072 / colNum) * (toCell - fromCell + 1)));
        for (int cellIndex = fromCell; cellIndex <= toCell; cellIndex++) {
            XWPFTableCell cell = table.getRow(row).getCell(cellIndex);
            if ( cellIndex == fromCell ) {
                // The first merged cell is set with RESTART merge value  
                cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);
            } else {
                // Cells which join (merge) the first one, are set with CONTINUE  
                cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE);
            }
        }
    }
 
    /**
     * 跨行合并
     *
     * @param table
     * @param col
     * @param fromRow
     * @param toRow
     */
    public static void mergeCellsVertically(XWPFTable table, int col,
                                            int fromRow, int toRow) {
        for (int rowIndex = fromRow; rowIndex <= toRow; rowIndex++) {
            XWPFTableCell cell = table.getRow(rowIndex).getCell(col);
            if (rowIndex == fromRow) {
                // The first merged cell is set with RESTART merge value
                cell.getCTTc().addNewTcPr().addNewVMerge()
                        .setVal(STMerge.RESTART);
            } else {
                // Cells which join (merge) the first one, are set with CONTINUE
                cell.getCTTc().addNewTcPr().addNewVMerge()
                        .setVal(STMerge.CONTINUE);
            }
        }
    }
 
    /**
     * 将文件转换成byte数组
     * @return
     */
    public byte[] fileToByte(File file){
        byte[] buffer = null;
        try
        {
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1)
            {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        }catch (FileNotFoundException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }
        return buffer;
    }
 
    /**
     * 下载
     * @param xdoc
     * @param request
     * @param response
     * @throws Exception
     */
    public static void downloadWord(XWPFDocument xdoc, HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setCharacterEncoding("UTF-8");
        //response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        response.setContentType("application/force-download");// 设置强制下载不打开
        response.setHeader("Content-disposition", "attachment");
        //刷新缓冲
        response.flushBuffer();
        OutputStream ouputStream = response.getOutputStream();
        //将word写入到response的输出流中,供页面下载该Excel文件
        xdoc.write(ouputStream);
        ouputStream.flush();
        ouputStream.close();
    }
}
posted @   岁月淡忘了谁  阅读(255)  评论(0编辑  收藏  举报
(评论功能已被禁用)
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
历史上的今天:
2014-07-13 java dom4j解析xml实例(2)
点击右上角即可分享
微信分享提示