1. 程式人生 > 程式設計 >Java Poi 在Excel中輸出特殊符號的實現方法

Java Poi 在Excel中輸出特殊符號的實現方法

最近的工作圍繞報表匯出,並沒有整合相應的報表外掛,只是使用了Poi。其中有一個需求,Excel中匯出特殊符號,如√、×等。在網上找尋了許久,沒有相關資料,故記錄分享一下。

思考良久,走了不少彎路,最後受 System.out.println() 啟發,實現方式真的超級簡單。每一個特殊符號,都對應一個Unicode編碼,我們只需要將特定的符號,轉變成Unicode編碼,進行輸出即可。

在這裡插入圖片描述

相應的程式碼輸出:

cell.setCellValue("\u221A");

另附自己編寫的Excel工具類,支援單表、主子表(可定製主表在前還是在後)、圖片、特殊符號等。

<dependency>
  <groupId>org.apache.poi</groupId>
  <artifactId>poi</artifactId>
  <version>4.1.2</version>
</dependency>
<dependency>
  <groupId>org.apache.poi</groupId>
  <artifactId>poi-ooxml</artifactId>
  <version>4.1.2</version>
</dependency>
<dependency>
  <groupId>org.apache.poi</groupId>
  <artifactId>poi-ooxml-schemas</artifactId>
  <version>4.1.2</version>
</dependency>
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<String,String> 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<T> {
  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<String,List<String>> fields,Collection<T> 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,String[] header,header,反射使用的children進行對映,可修改
   * @param pattern 日期格式
   * @param path  檔案路徑
   * @param childBefore 子表在前
   */
  public void exportExcel(String title,String pattern,pattern,childBefore);
  }

  /**
   * 匯出檔案到本地
   * @param fields 欄位集合 主表key為entity,反射使用的children進行對映,可修改
   * @param response http
   */
  public void exportExcel(String title,HttpServletResponse response){
    createExcelHSSF(title,response);
  }

  /**
   * 匯出檔案到本地
   * @param fields 欄位集合 主表key為entity,反射使用的children進行對映,可修改
   * @param pattern 日期格式
   * @param response http
   */
  public void exportExcel(String title,response);
  }
  /**
   * 頁面下載excel
   * @param title
   * @param fields
   * @param header
   * @param dataset
   * @param pattern
   * @param response
   */
  private void createExcelHSSF(String title,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,false);
    httpExcelHSSF(workbook,response);
  }

  /**
   * 輸出到指定路徑
   * @param title
   * @param fields
   * @param header
   * @param dataset
   * @param pattern
   * @param path
   * @param childBefore
   */
  private void createExcelHSSF(String title,boolean childBefore){
    createExcel2003(title,childBefore);
    ioExcelHSSF(workbook,path);
  }

  /**
   * 公共方法,建立excel 2003版
   * @param title
   * @param fields
   * @param header
   * @param dataset
   * @param pattern
   * @param childBefore
   */
  private void createExcel2003(String title,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<String> entityFields = fields.get("entity");
    // 獲取子表屬性欄位
    List<String> 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 <entityFields.size(); i++){
        Object value = getValue(t,entityFields.get(i));
        // 建立單元格
        if(childBefore){
          if(ExcelPercentField.percentFiledMap.containsKey(entityFields.get(i))){
            createTableCell(row.createCell(i+childColumnLength),value,percentStyle,rowspan);
          }else{
            createTableCell(row.createCell(i+childColumnLength),normalStyle,rowspan);
          }
        }else{
          if(ExcelPercentField.percentFiledMap.containsKey(entityFields.get(i))){
            createTableCell(row.createCell(i),rowspan);
          }else{
            createTableCell(row.createCell(i),rowspan);
          }
        }
      }
      // 子表字段
      if(childFields !=null && childFields.size() > 0){
        if(children !=null ){
          List list = (ArrayList)children;
          for(int i = 0;i <list.size(); i++){
            if(i >0){
              rowNum++;
              row = sheet.createRow(rowNum);
            }
            for(int j = 0;j<childFields.size();j++){
              Object value = getValue(list.get(i),childFields.get(j));
              if(childBefore){
                if(ExcelPercentField.percentFiledMap.containsKey(childFields.get(j))){
                  createTableCell(row.createCell(j ),rowspan);
                }else{
                  createTableCell(row.createCell(j ),rowspan);
                }
              }else{
                if(ExcelPercentField.percentFiledMap.containsKey(childFields.get(j))){
                  createTableCell(row.createCell(j +entityColumnLength),rowspan);
                }else{
                  createTableCell(row.createCell(j +entityColumnLength),rowspan);
                }

              }
            }
          }
        }
      }
      // 如果需要合併行
      if(rowspan > 0){
        for(int i = 0;i<entityFields.size();i++){
          CellRangeAddress cellRange = null;
          if(childBefore){
            cellRange= new CellRangeAddress(rowNum-rowspan,rowNum,i+childColumnLength,i+childColumnLength);
          }else{
            cellRange = new CellRangeAddress(rowNum-rowspan,i,i);
          }
          sheet.addMergedRegion(cellRange);
          //新增邊框
          RegionUtil.setBorderTop(BorderStyle.THIN,cellRange,sheet);
          RegionUtil.setBorderBottom(BorderStyle.THIN,sheet);
          RegionUtil.setBorderLeft(BorderStyle.THIN,sheet);
          RegionUtil.setBorderRight(BorderStyle.THIN,sheet);
          RegionUtil.setTopBorderColor(HSSFColor.HSSFColorPredefined.GREEN.getIndex(),sheet);
          RegionUtil.setBottomBorderColor(HSSFColor.HSSFColorPredefined.GREEN.getIndex(),sheet);
          RegionUtil.setLeftBorderColor(HSSFColor.HSSFColorPredefined.GREEN.getIndex(),sheet);
          RegionUtil.setRightBorderColor(HSSFColor.HSSFColorPredefined.GREEN.getIndex(),sheet);
        }
      }
    }
    sheet.autoSizeColumn(2);
    setSizeColumn(sheet,entityColumnLength+childColumnLength);
  }
  /**
   * 初始化構建工作簿
   */
  private void initWorkBook(){
    // 建立一個工作簿
    workbook = HSSFWorkbookFactory.createWorkbook();
    // 建立一個sheet
    sheet = workbook.createSheet();
    // 預設表格列寬
    sheet.setDefaultColumnWidth(18);
    patriarch = sheet.createDrawingPatriarch();
  }
  /**
   * 建立Excel標題
   * @param title 標題
   * @param colspan 合併列
   * @param headerStyle 樣式
   */
  private void createTableTitle(String title,int colspan,HSSFCellStyle headerStyle) {
    if(StringUtils.isBlank(title)){
      return;
    }
    HSSFRow row = sheet.createRow(rowNum);
    row.setHeightInPoints(30f);
    HSSFCell cell = row.createCell(0);
    sheet.addMergedRegion(new CellRangeAddress(rowNum,colspan));
    cell.setCellStyle(headerStyle);
    cell.setCellValue(title);
    rowNum ++;
  }
  /**
   * 建立Excel表頭
   * @param header
   * @param headerStyle
   */
  private void createTableHead(String[] header,HSSFCellStyle headerStyle) {
    if(header ==null || header.length <1){
      return;
    }
    HSSFRow row = sheet.createRow(rowNum);
    HSSFCell cell;
    for (int i = 0; i < header.length; i++){
      cell = row.createCell(i);
      cell.setCellStyle(headerStyle);
      cell.setCellValue(header[i]);
      cell.setCellType(CellType.STRING);
    }
  }

  /**
   * 建立單元格
   * @param cell
   * @param value
   * @param normalStyle
   */
  private void createTableCell(HSSFCell cell,Object value,HSSFCellStyle normalStyle,int rowspan) {
    cell.setCellStyle(normalStyle);
    if (value ==null){
      return;
    }
    if(value instanceof Number){
      cell.setCellType(CellType.NUMERIC);
      cell.setCellValue(Double.parseDouble(value.toString()));
    //日期
    } else if(value instanceof Date){
      cell.setCellType(CellType.STRING);
      cell.setCellValue(DateUtils.parseDateToStr(pattern,(Date)value));
    // 圖片
    } else if(value instanceof byte[]){
      cell.getRow().setHeightInPoints(80);
      sheet.setColumnWidth(cell.getColumnIndex(),(short) (34.5 * 110));
      HSSFClientAnchor anchor = new HSSFClientAnchor(0,1023,255,(short) cell.getColumnIndex(),rowNum);
      anchor.setAnchorType(ClientAnchor.AnchorType.MOVE_DONT_RESIZE);
      patriarch.createPicture(anchor,workbook.addPicture(
          (byte[])value,HSSFWorkbook.PICTURE_TYPE_JPEG));

    }else if(value instanceof Boolean){
      cell.setCellType(CellType.STRING);
      if((boolean)value){
        cell.setCellValue("\u221A");
      }
      // 全部當作字串處理
    }else{
      cell.setCellType(CellType.STRING);
      cell.setCellValue(new HSSFRichTextString(String.valueOf(value)));
    }
  }

  /**
   * 建立標題行
   * @param workbook
   * @return
   */
  private HSSFCellStyle getTitleStyle(HSSFWorkbook workbook) {
    HSSFCellStyle style = getNormalStyle(workbook);
    style.getFont(workbook).setFontHeightInPoints((short)12);
    style.setAlignment(HorizontalAlignment.CENTER);
    style.setVerticalAlignment(VerticalAlignment.CENTER);
    return style;
  }

  /**
   * 建立尾部合計行
   * @param workbook
   * @return
   */
  private HSSFCellStyle getFooterStyle(HSSFWorkbook workbook) {
    HSSFCellStyle style = getNormalStyle(workbook);
    style.getFont(workbook).setFontHeightInPoints((short)12);
    style.setAlignment(HorizontalAlignment.CENTER);
    style.setVerticalAlignment(VerticalAlignment.CENTER);
    style.setFillForegroundColor(IndexedColors.LIME.getIndex());
    style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
    return style;
  }

  /**
   * 建立表頭樣式
   * @param workbook
   * @return
   */
  private HSSFCellStyle getHeaderStyle(HSSFWorkbook workbook) {
    HSSFCellStyle style = getNormalStyle(workbook);
    style.getFont(workbook).setFontHeightInPoints((short)11);
    style.setAlignment(HorizontalAlignment.CENTER);
    style.setVerticalAlignment(VerticalAlignment.CENTER);
    style.setFillForegroundColor(IndexedColors.LIME.getIndex());
    style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
    HSSFPalette palette = workbook.getCustomPalette();
    palette.setColorAtIndex(IndexedColors.LIME.getIndex(),(byte)198,(byte)224,(byte)180);
    return style;
  }

  /**
   * 百分比格式
   * @param workbook
   * @return
   */
  private HSSFCellStyle createPercentStyle(HSSFWorkbook workbook){
    HSSFCellStyle style = getNormalStyle(workbook);
    style.setDataFormat(HSSFDataFormat.getBuiltinFormat("0.00%"));
    return style;
  }

  /**
   * 建立普通樣式
   * @param workbook
   * @return
   */
  private HSSFCellStyle getNormalStyle(HSSFWorkbook workbook){
    // 建立字型
    HSSFFont font = workbook.createFont();
    font.setFontHeightInPoints((short)10);
    // 構建樣式
    HSSFCellStyle style = workbook.createCellStyle();
    // 設定邊框
    style.setBorderTop(BorderStyle.THIN);
    style.setBorderRight(BorderStyle.THIN);
    style.setBorderBottom(BorderStyle.THIN);
    style.setBorderLeft(BorderStyle.THIN);
    style.setTopBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex());
    style.setRightBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex());
    style.setBottomBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex());
    style.setLeftBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex());
    style.setAlignment(HorizontalAlignment.CENTER);
    style.setVerticalAlignment(VerticalAlignment.CENTER);
    style.setFont(font);
    // 字型預設換行
    style.setWrapText(true);
    return style;
  }


  /**
   * 反射獲取值
   * @param t
   * @param fieldName
   * @param <E>
   * @return
   */
  private <E> 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<size;i++){
      int columnWidth = sheet.getColumnWidth(i) / 256;
      for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) {
        HSSFRow currentRow;
        //當前行未被使用過
        if (sheet.getRow(rowNum) == null) {
          currentRow = sheet.createRow(rowNum);
        } else {
          currentRow = sheet.getRow(rowNum);
        }

        if (currentRow.getCell(i) != null) {
          HSSFCell currentCell = currentRow.getCell(i);
//          if(rowNum==sheet.getLastRowNum()){
//            HSSFCellStyle style = currentCell.getCellStyle();
//            style.setFillForegroundColor(IndexedColors.LIME.getIndex());
//            style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
//            currentCell.setCellStyle(style);
//          }
          if (currentCell.getCellType() == CellType.STRING) {
            int length = currentCell.getStringCellValue().getBytes().length;
            if (columnWidth < length) {
              columnWidth = length;
            }
          }
        }
      }
      sheet.setColumnWidth(i,columnWidth * 256);
    }
  }
}

效果圖如下:

在這裡插入圖片描述

但仍遇到一個問題,主子表結構匯出,如果圖片在主表,合併行之後,圖片並不會居中,並且第一行會被撐開,有沒有比較簡單的方式進行處理(不想重新計算錨點,然後定高輸出)?

在這裡插入圖片描述

到此這篇關於Java Poi 在Excel中輸出特殊符號的文章就介紹到這了,更多相關java poi excel 輸出特殊符號內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!