当前位置:   article > 正文

Java导出Excel以及word富文本_富文本导出到excel

富文本导出到excel

1、添加pom依赖

<dependency>
	<groupId>org.apache.poi</groupId>
	<artifactId>poi</artifactId>
	<version>3.17</version>
</dependency>
  • 1
  • 2
  • 3
  • 4
  • 5

2、富文本导出

package com.sxnxcloud.regulation.utils;

import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;

/**
 * @ClassName: WordUtils
 * @Description: TODO
 * @Author yuf
 * @Date 2020/3/24 17:18
 */
public class WordUtils {
    public static void exportWord(HttpServletRequest request, HttpServletResponse response, String title, String text) {
        try {
            //word内容
            String content="<html><body>" +
                    "<p style=\"text-align: center;\"><span style=\"font-family: 黑体, SimHei; font-size: 24px;\">"
                    + title + "</span></p>" + text + "</body></html>";
            byte b[] = content.getBytes("GBK");  //这里是必须要设置编码的,不然导出中文就会乱码。
            ByteArrayInputStream bais = new ByteArrayInputStream(b);//将字节数组包装到流中

            /*
             * 关键地方
             * 生成word格式 */
            POIFSFileSystem poifs = new POIFSFileSystem();
            DirectoryEntry directory = poifs.getRoot();
            directory.createDocument("WordDocument", bais);
            //输出文件
            //输出文件
            request.setCharacterEncoding("utf-8");
            response.setContentType("application/msword");//导出word格式
            response.addHeader("Content-Disposition", "attachment;filename=" +title+".doc");
            ServletOutputStream ostream = response.getOutputStream();
            poifs.writeFilesystem(ostream);
            bais.close();
            ostream.close();
            poifs.close();
        }catch(Exception e){
            e.printStackTrace();
        }

    }

}
  • 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

3、导出Excel

package com.sxnxcloud.regulation.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.CellStyle;
import org.gocom.coframe.sdk.CofConstants;
import org.gocom.coframe.sdk.exception.CofErrorCode;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Slf4j
public class ExcelUtils {
    // 字符编码格式
    private static String charsetCode = "utf-8";
    public static void download(HttpServletRequest request, HttpServletResponse response, String filePath, String fileName) {

        try {
            File file = new File(filePath);
            /**
             * 中文乱码解决
             */
            String type = request.getHeader("User-Agent").toLowerCase();
            if (type.indexOf("firefox") > 0 || type.indexOf("chrome") > 0) {
                /**
                 * 谷歌或火狐
                 */
                fileName = new String(fileName.getBytes("gbk"), "ISO-8859-1");
            } else {
                /**
                 * IE
                 */
                fileName = URLEncoder.encode(fileName, charsetCode);
            }
            // 设置响应的头部信息
            response.setHeader("content-disposition", "attachment;filename=" + fileName);
            // 设置响应内容的类型
            response.setContentType(getFileContentType(fileName) + "; charset=" + charsetCode);
            // 设置响应内容的长度
            response.setContentLength((int) file.length());
            // 输出
            outStream(new FileInputStream(file), response.getOutputStream());
        } catch (Exception e) {
            System.out.println("执行downloadFile发生了异常:" + e.getMessage());
        }
    }
    /**
     * 基础字节数组输出
     */
    private static void outStream(InputStream is, OutputStream os) {
        try {
            byte[] buffer = new byte[10240];
            int length = -1;
            while ((length = is.read(buffer)) != -1) {
                os.write(buffer, 0, length);
                os.flush();
            }
        } catch (Exception e) {
            System.out.println("执行 outStream 发生了异常:" + e.getMessage());
        } finally {
            try {
                os.close();
            } catch (IOException e) {
            }
            try {
                is.close();
            } catch (IOException e) {
            }
        }
    }
    /**
     * 文件的内容类型
     */
    private static String getFileContentType(String name){
        String result = "";
        String fileType = name.toLowerCase();
        if (fileType.endsWith(".png")) {
            result = "image/png";
        } else if (fileType.endsWith(".gif")) {
            result = "image/gif";
        } else if (fileType.endsWith(".jpg") || fileType.endsWith(".jpeg")) {
            result = "image/jpeg";
        } else if(fileType.endsWith(".svg")){
            result = "image/svg+xml";
        }else if (fileType.endsWith(".doc")) {
            result = "application/msword";
        } else if (fileType.endsWith(".xls")) {
            result = "application/x-excel";
        } else if (fileType.endsWith(".zip")) {
            result = "application/zip";
        } else if (fileType.endsWith(".pdf")) {
            result = "application/pdf";
        } else {
            result = "application/octet-stream";
        }
        return result;
    }

    private String outfile;

    /**
     *
     * @param header 为存放表头的数组,将显示在表格中
     * @param bodyList<HashMap<String,String>> 为存放表格内容的集合,泛型为HashMap<String,String>,key值应与header中的表头名完全一致
     * @return
     */
    public String generatorXls(String[] header, List<HashMap<String,String>> bodyList){
        String files = CofConstants.EXCEL_CREAT_FILES;
        Date date = new Date();
        SimpleDateFormat datef = new SimpleDateFormat("yyyyMMdd");
        String dates = datef.format(date);
        files = files+dates;
        String filesName = generatorXls(header,bodyList,files);
        return filesName;
    }

    /**
     *
     * @param header 为存放表头的数组,将显示在表格中
     * @param bodyList<HashMap<String,String>> 为存放表格内容的集合,泛型为HashMap<String,String>,key值应与header中的表头名完全一致
     * @param filePath 生成文件路径名
     * @return
     */
    public String generatorXls(String[] header, List<HashMap<String,String>> bodyList,String filePath) {

        for(int i = 0; i < bodyList.size(); i++){
            if(bodyList.get(i).size()>header.length){
                throw CofErrorCode.EXCEL_LENGTH_ERROR.runtimeException();
            }

        }
        String pathLastChar = filePath.substring(filePath.length()-1);
        if(!"/".equals(pathLastChar)){
            filePath = filePath+"/";
        }
        Date date = new Date();
        SimpleDateFormat datef = new SimpleDateFormat("yyyyMMdd");
        SimpleDateFormat timef = new SimpleDateFormat("HHmmssSSS");
        String dates = datef.format(date);
        String times = timef.format(date);
        String fileName ="sxnxOA_"+dates+times+".xls";

        //EXCEL生成后本地路径
        String excelFullPath=filePath;
        File fold = new File(excelFullPath);
        File file = new File(excelFullPath + fileName);
        if (!fold.exists()) {
            fold.mkdirs();
            if (!file.exists()) {
                try {
                    file.createNewFile();
                } catch (IOException e) {
                    throw CofErrorCode.CREAT_FILES_FAILED.runtimeException();
                }
            }
        }
        log.info("=====创建文件成功========"+excelFullPath+fileName);

        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet();
        HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
        addHeadRow(sheet,header);

        int bodyNum = bodyList.size();
        for(int i = 0; i < bodyNum; i++) {
            bodyList.get(i);
            HSSFRow row = sheet.createRow(i+1);
            for(int j = 0; j < header.length; j++) {
                row.createCell(j).setCellValue(bodyList.get(i).get(header[j]));
            }
        }
        SavePic(excelFullPath+fileName);
        sheetStyle(sheet,header); // 最后添加样式
        // 将内存对象输出到文件
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(this.outfile);
            wb.write(fos);
        } catch (Exception e) {
            throw CofErrorCode.CREAT_FILES_FAILED.runtimeException();
        } finally {
            try {
                if (fos != null)
                    fos.close();
            } catch (IOException e) {
                throw CofErrorCode.CREAT_FILES_FAILED.runtimeException();
            }
        }
        return excelFullPath+fileName;
    }


    private void addHeadRow(HSSFSheet sheet,String[] header) {
        int headerLength = header.length;
        HSSFRow row = sheet.createRow(0);
        for(int i = 0; i < headerLength; i++) {
            row.createCell(i).setCellValue(header[i]);
        }
        row.setHeightInPoints((float) 12.75);
    }

    private void sheetStyle(HSSFSheet sheet,String[] header) {
        int headerLength = header.length;
        for(int i = 0; i < headerLength; i++) {
            sheet.setColumnWidth(i, 5000);
        }


        int rows = sheet.getLastRowNum();
        log.info("共计写入行:" + (rows + 1));

        // 头部样式
        HSSFCellStyle headStyle = sheet.getWorkbook().createCellStyle();
//        headStyle.setAlignment(CellStyle.ALIGN_CENTER);// 水平居中
//        headStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);// 垂直居中
//        headStyle.setFillBackgroundColor(HSSFColor.LIGHT_GREEN.index); //设置背景色
//        headStyle.setFillForegroundColor(HSSFColor.LIGHT_GREEN.index);// 设置前景色
//        headStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
//        headStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 下边框
//        headStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);// 左边框
//        headStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);// 上边框
//        headStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);// 右边框

        for(int j = 0; j < header.length; j++) {

            sheet.getRow(0).getCell(j).setCellStyle(headStyle);
        }

        // 给所有单元格添加边框
        HSSFCellStyle dataStyle = sheet.getWorkbook().createCellStyle();
//        dataStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 下边框
//        dataStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);// 左边框
//        dataStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);// 上边框
//        dataStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);// 右边框

        for (int i = 1; i <= rows; i++) {//从第二行开始
            for(int j = 0; j < header.length; j++) {
                sheet.getRow(i).getCell(j).setCellStyle(dataStyle);
            }
        }
    }

    public void SavePic(String outfile) {
        if (outfile != null)
            this.outfile = outfile;
    }
}
  • 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
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/476275
推荐阅读
相关标签
  

闽ICP备14008679号