Java Poi 在Excel中输出特殊符号的实现方法

最近的工作围绕报表导出,并没有集成相应的报表插件,只是使用了Poi。其中有一个需求,Excel中导出特殊符号,如√、×等。在网上找寻了许久,没有相关资料,故记录分享一下。

思考良久,走了不少弯路,最后受 System.out.println() 启发,实现方式真的超级简单。每一个特殊符号,都对应一个Unicode编码,我们只需要将特定的符号,转变成Unicode编码,进行输出即可。

Java Poi 在Excel中输出特殊符号的实现方法_第1张图片

相应的代码输出:

cell.setCellValue("\u221A");

另附自己编写的Excel工具类,支持单表、主子表(可定制主表在前还是在后)、图片、特殊符号等。


  org.apache.poi
  poi
  4.1.2


  org.apache.poi
  poi-ooxml
  4.1.2


  org.apache.poi
  poi-ooxml-schemas
  4.1.2
package com.king.tools.util;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ππ
 * @date 2020-6-22 17:03
 * 导出的Excel中,百分比
 */

public class ExcelPercentField {
  public final static Map percentFiledMap = new HashMap<>();
  static {
  		// 根据实际情况进行设置
    percentFiledMap.put("a","a");
    percentFiledMap.put("b","b");
    percentFiledMap.put("c","c");
  }
}
package com.king.tools.util;

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.RegionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.*;

/**
 * @author ππ
 * @date 2020-6-10 14:45
 * excel 导出通用类
 * 采用反射生成
 * 目前仅支持导出slx,暂不支持导出xlsx格式
 */

public class ExcelExport {
  Logger logger = LoggerFactory.getLogger(ExcelExport.class);
  private HSSFWorkbook workbook;
  private HSSFSheet sheet;
  private int rowNum;
  private HSSFPatriarch patriarch ;
  private String fileName;
  private int version;

  public ExcelExport(){}
  public ExcelExport(String fileName, int version) {
    this.fileName = fileName;
    this.version = version;
  }

  /**
   * 导出Excel到指定位置
   * @param fields 字段集合 主表key为entity,子表key为children
   * @param dataset 数据集合 注意:如果为主子表,主表中,子表集合对应的属性名必须为children,反射使用的children进行映射,可修改
   * @param path  文件路径
   */
  public void exportExcel(String title, Map> fields, Collection dataset, String path,boolean childBefore){
    createExcelHSSF(title,fields,null,dataset,DateUtils.YYYY_MM_DD,path,childBefore);
  }

  /**
   * 导出Excel到指定位置
   * @param fields 字段集合 主表key为entity,子表key为children
   * @param header 表头数组
   * @param dataset 数据集合 注意:如果为主子表,主表中,子表集合对应的属性名必须为children,反射使用的children进行映射,可修改
   * @param path  文件路径
   * @param childBefore 子表在前 默认false
   */
  public void exportExcel(String title,Map> fields,String[] header,Collection dataset,String path,boolean childBefore){
    createExcelHSSF(title,fields,header,dataset,DateUtils.YYYY_MM_DD,path,childBefore);
  }

  /**
   * 导出Excel到指定位置
   * @param fields 字段集合 主表key为entity,子表key为children
   * @param header 表头数组
   * @param dataset 数据集合 注意:如果为主子表,主表中,子表集合对应的属性名必须为children,反射使用的children进行映射,可修改
   * @param pattern 日期格式
   * @param path  文件路径
   * @param childBefore 子表在前
   */
  public void exportExcel(String title,Map> fields,String[] header,Collection dataset,String pattern,String path,boolean childBefore){
    createExcelHSSF(title,fields,header,dataset,pattern,path,childBefore);
  }

  /**
   * 导出文件到本地
   * @param fields 字段集合 主表key为entity,子表key为children
   * @param dataset 数据集合 注意:如果为主子表,主表中,子表集合对应的属性名必须为children,反射使用的children进行映射,可修改
   * @param response http
   */
  public void exportExcel(String title,Map> fields, Collection dataset, HttpServletResponse response){
    createExcelHSSF(title,fields,null,dataset,DateUtils.YYYY_MM_DD,response);
  }

  /**
   * 导出文件到本地
   * @param fields 字段集合 主表key为entity,子表key为children
   * @param header 表头数组
   * @param dataset 数据集合 注意:如果为主子表,主表中,子表集合对应的属性名必须为children,反射使用的children进行映射,可修改
   * @param response http
   */
  public void exportExcel(String title, Map> fields, String[] header, Collection dataset, HttpServletResponse response){
    createExcelHSSF(title,fields,header,dataset,DateUtils.YYYY_MM_DD,response);
  }

  /**
   * 导出文件到本地
   * @param fields 字段集合 主表key为entity,子表key为children
   * @param header 表头数组
   * @param dataset 数据集合 注意:如果为主子表,主表中,子表集合对应的属性名必须为children,反射使用的children进行映射,可修改
   * @param pattern 日期格式
   * @param response http
   */
  public void exportExcel(String title, Map> fields, String[] header, Collection dataset, String pattern, HttpServletResponse response){
    createExcelHSSF(title,fields,header,dataset,pattern,response);
  }
  /**
   * 页面下载excel
   * @param title
   * @param fields
   * @param header
   * @param dataset
   * @param pattern
   * @param response
   */
  private void createExcelHSSF(String title, Map> fields, String[] header, Collection dataset, String pattern, HttpServletResponse response){
    response.reset(); // 清除buffer缓存
    // 指定下载的文件名
    response.setHeader("Content-Disposition", "attachment;filename=contacts" +(StringUtils.isBlank(fileName)? DateUtils.dateTimeNow() : fileName) + ".xls");
    response.setContentType("application/vnd.ms-excel;charset=UTF-8");
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Cache-Control", "no-cache");
    response.setDateHeader("Expires", 0);
    createExcel2003(title,fields,header,dataset,pattern, false);
    httpExcelHSSF(workbook,response);
  }

  /**
   * 输出到指定路径
   * @param title
   * @param fields
   * @param header
   * @param dataset
   * @param pattern
   * @param path
   * @param childBefore
   */
  private void createExcelHSSF(String title,Map> fields,String[] header,Collection dataset,String pattern,String path,boolean childBefore){
    createExcel2003(title,fields,header,dataset,pattern,childBefore);
    ioExcelHSSF(workbook,path);
  }

  /**
   * 公共方法,创建excel 2003版
   * @param title
   * @param fields
   * @param header
   * @param dataset
   * @param pattern
   * @param childBefore
   */
  private void createExcel2003(String title, Map> fields, String[] header, Collection dataset, String pattern, boolean childBefore){
    // 初始化构建
    initWorkBook();
    // 生成样式
    HSSFCellStyle titleStyle = getTitleStyle(workbook);
    HSSFCellStyle headerStyle = getHeaderStyle(workbook);
    HSSFCellStyle normalStyle = getNormalStyle(workbook);
    HSSFCellStyle footerStyle = getFooterStyle(workbook);
    HSSFCellStyle percentStyle = createPercentStyle(workbook);
    // 创建表头
    createTableTitle(title,header.length-1,titleStyle);
    // 生成标题行
    createTableHead(header,headerStyle);
    // 迭代集合
    Iterator it = dataset.iterator();
    // 获取主表属性字段
    List entityFields = fields.get("entity");
    // 获取子表属性字段
    List childFields = fields.get("children");
    // 主表字段长度
    int entityColumnLength = entityFields.size();
    int childColumnLength = 0;
    if(childFields !=null){
      childColumnLength = childFields.size();
    }
    // 合并行
    int rowspan = 0;
    // 每个对象的子表数据
    Object children = null;
    HSSFRow row;
    HSSFCell cell;
    while (it.hasNext()){
      rowNum ++;
      T t = (T) it.next();
      row = sheet.createRow(rowNum);
      // 确定合并行数
      if(childFields !=null && childFields.size() > 0){
        children = getValue(t,"children");
        if(children !=null && ((ArrayList)children).size()>0){
          rowspan = ((ArrayList)children).size()-1;
        }
      }
      // 主表字段
      for(int i = 0; i  0){
        if(children !=null ){
          List list = (ArrayList)children;
          for(int i = 0;i 0){
              rowNum++;
              row = sheet.createRow(rowNum);
            }
            for(int j = 0;j 0){
        for(int i = 0;i
   * @return
   */
  private  Object getValue(E t,String fieldName){
    String methodName = "get"
        + fieldName.substring(0, 1).toUpperCase()
        + fieldName.substring(1);
    try {
      Method method = t.getClass().getMethod(methodName);
      method.setAccessible(true);
      Object value = method.invoke(t);
      return value;
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }
  /**
   * 输出IO流
   * @param workbook
   * @param path
   * @return
   */
  private void ioExcelHSSF(HSSFWorkbook workbook, String path){
    OutputStream ops =null;
    if(StringUtils.isBlank(fileName)){
      path = path + DateUtils.dateTimeNow() +".xls";
    } else {
      path = path + fileName + ".xls";
    }
    try {
      ops = new FileOutputStream(path);
      workbook.write(ops);
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }finally {
      if(ops != null){
        try {
          ops.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }

  private void httpExcelHSSF(HSSFWorkbook workbook, HttpServletResponse response){
    OutputStream ops = null;
    try {
      ops = response.getOutputStream();
      response.flushBuffer();
      workbook.write(ops);
    } catch (IOException e) {
      e.printStackTrace();
      if(ops !=null){
        try {
          ops.close();
        } catch (IOException ex) {
          ex.printStackTrace();
        }
      }
    }
  }

  /**
   * 自适应列宽
   * @param sheet
   * @param size 列数
   */
  private void setSizeColumn(HSSFSheet sheet, int size) {
    for(int i =0;i 
 

效果图如下:

Java Poi 在Excel中输出特殊符号的实现方法_第2张图片

但仍遇到一个问题,主子表结构导出,如果图片在主表,合并行之后,图片并不会居中,并且第一行会被撑开,有没有比较简单的方式进行处理(不想重新计算锚点,然后定高输出)?

Java Poi 在Excel中输出特殊符号的实现方法_第3张图片

到此这篇关于Java Poi 在Excel中输出特殊符号的文章就介绍到这了,更多相关java poi excel 输出特殊符号内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

你可能感兴趣的:(Java Poi 在Excel中输出特殊符号的实现方法)