1、添加pom依赖

<dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>3.17</version>
</dependency>

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();}}}

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

Java导出Excel以及word富文本相关推荐

  1. java导出excel与word文档

    导出excel与word 依赖如下 <!--导出excel文档,easyexcel的依赖:为了防止poi版本冲突--><dependency><groupId>co ...

  2. Java导出Excel和Word

    1.导出word a.打开需要导出的word模板,另存为xml文件 b.java中使用 //生成word文件 public void downWordAcceptRegist(HttpServletR ...

  3. Java导出Excel或word jsp页面直接转的方式

    2.jsp页面直接转成Excel或是word方式: 首先,在web.xml上添加上告诉浏览器该资源的媒体类型: <mime-mapping><extension>doc< ...

  4. Java 导出Excel利用模版导出

    Java导出Excel和word的方式大体相同 1.Excel模版导出到页面下载 首先,导入依赖在pom.xml中我选择的事1.03的版本 第二.在项目或是自己需要的地方建立个文件夹放导出文件的模版, ...

  5. Java导出数据到Word模板中

    Java导出数据到Word模板. 前言 网上的方案 需求介绍 模板 简介 使用体验 poi-tl Freemarker 操作步骤 总结 前言 相信很多人都会遇到Java导出的业务,Java导出主要有导 ...

  6. java导出excel(easypoi)

    介绍 easypoi功能如同名字easy,主打的功能就是容易,让一个没见接触过poi的人员 就可以方便的写出Excel导出,Excel模板导出,Excel导入,Word模板导出,通过简单的注解和模板 ...

  7. java导出excel设置行高列宽_使用POI生成Excel文件,可以自动调整excel列宽

    //autoSizeColumn()方法自动调整excel列宽 importjava.io.FileOutputStream; importorg.apache.poi.hssf.usermodel. ...

  8. java导出excel文件名_怎么解决java导出excel时文件名乱码

    怎么解决java导出excel时文件名乱码 发布时间:2020-06-19 16:59:00 来源:亿速云 阅读:137 作者:元一 java解决导出Excel时文件名乱码的方法示例:String a ...

  9. 使用EasyPoi根据模板导出Excel或word文档

    接着上篇文章 Java根据模板导出Excel并生成多个Sheet 简单介绍下EasyPoi的使用,直接上代码吧 首先当然是先引入jar包了,看下图 其次,还是贴代码吧看实例,下面是根据模板导出的工具类 ...

  10. java导出excel数字格式_POI 导出excel带小数点的数字格式显示不对解决方法

    最近看到了一个问题就是java导出excel中带小数点的数字显示不对, 比如我想在excel中第一行显示:  3,000.0 但是在excle中导出的格式总是不带小数点 3000(非文本格式),而且也 ...

最新文章

  1. linux系统上搭建vsftp服务
  2. [Voice communications] 看得到的音频流
  3. 净资产滚动率_净资产的结构
  4. java责任链模式审批请假_Java使用责任链模式处理学生请假问题详解
  5. JavaScript(DOM编程一)
  6. 一步步实现 Redis 搜索引擎 1
  7. 关于如何在Listener中注入service和ServletContextListener源码分析
  8. java读取、生成图片
  9. Http代理抓包 Fiddler与Charles
  10. mysql慢查询日志配置_MySQL 慢查询日志配置与简析
  11. Wazuh的rootkit扫描性能优化
  12. webstorm主题配置
  13. Spring实战(第4版)第1章 Spring之旅
  14. 论文中期报告要怎么写?
  15. Ubuntu桌面快捷方式
  16. hiho 满减优惠(暴力)
  17. [Android] [Hybrid APP开发简述]
  18. rm -rf和rm -f和rm
  19. css直角线_css斜切角 斜边 倒角
  20. keras版yolov3绘制acc和loss曲线

热门文章

  1. 解决no st-link detected问题
  2. 用OpenGL+C++写的一个小的3D游戏---3D贪吃蛇
  3. 深度学习 用户画像_基于人工智能的用户画像构建
  4. 2024北京养老展,CISSE中国国际养老服务业博览会
  5. ha linux 设置虚拟ip_linux配置虚拟IP--VIP
  6. Python-类02(乌龟吃鱼游戏)
  7. Linux常用文本操作命令整理
  8. 命令行升级 Cisco ios AP c3702i c3602i c2702i 1702i胖固件 Autonomous ios image ap3g2-k9w7-tar.153-3.JPO.tar
  9. 直线生成算法---逐点比较法
  10. 真的被CNBETA的编辑气死了