POI导出EXCEL模板数据

 1.apache poi 3.14+版本

package com.jd.medicine.erp.shop.service.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import lombok.extern.slf4j.Slf4j;

/**
 * 描述:ImpAndExpExcel
 * @author shizhenwei5
 * @date 2020年3月17日
 */
@Slf4j
public class ExcelExportUtils {
    
    /**
     * 描述:导出xlsx
     * @author shizhenwei5
     * @date 2020年3月23日
     * @param data 导出数据
     * @param fields 导出列属性
     * @param template 导出模板流
     * @param fileName 导出文件名称
     * @return
     * @throws IOException
     */
    public static void doExportXlsx(Object data, String[] fields, InputStream template,String fileName) throws IOException{
        doExportXlsx(data, fields, null, template, null, fileName);
    }
    
    /**
     * 描述:导出xlsx
     * @author shizhenwei5
     * @date 2020年3月23日
     * @param data 导出数据
     * @param fields 导出列属性
     * @param template 导出模板流
     * @param rowNum 模板第几行导出
     * @param fileName 导出文件名称
     * @return
     * @throws IOException
     */
    public static void doExportXlsx(Object data, String[] fields, InputStream template,Integer rowNum,String fileName) throws IOException{
        doExportXlsx(data, fields, null, template, rowNum, fileName);
    }
    
    /**
     * 描述:导出xlsx
     * @author shizhenwei5
     * @date 2020年3月23日
     * @param data 导出数据
     * @param fields 导出列属性
     * @param fieldTypes 导出列属性类型
     * @param template 导出模板流
     * @param rowNum 模板第几行导出
     * @param fileName 导出文件名称
     * @return
     * @throws IOException
     */
    public static void doExportXlsx(Object data,String[] fields,String[] fieldTypes,InputStream template,Integer rowNum,String fileName) throws IOException{
        XSSFWorkbook workbook = getXSSFWorkbook(data, fields, fieldTypes, template,rowNum);
        ServletOutputStream out = null;
        try {
            if(!fileName.endsWith(".xlsx")) {
                fileName += ".xlsx";
            }
            HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/octet-stream; charset=UTF-8");
            response.addHeader("Content-Disposition", "attachment; filename=\""+new String(fileName.getBytes("GB2312"),"ISO8859-1")+"\";");// 
            out = response.getOutputStream();
            workbook.write(out);
            out.flush();
            //workbook.close();
        } catch (IOException e) {
            log.info("#ExcelExport.doExportXlsx 异常:{}", e);
            e.printStackTrace();
        }
    }
    
    /**
     * 描述:获取导出XSSFWorkbook
     * @author shizhenwei5
     * @date 2020年3月23日
     * @param data 导出数据
     * @param fields 导出列属性
     * @param template 导出模板流
     * @return
     * @throws IOException
     */
    public static XSSFWorkbook getXSSFWorkbook(Object data, String[] fields, InputStream template) throws IOException {
        return getXSSFWorkbook(data, fields, null, template, null);
    }
    
    /**
     * 描述:获取导出XSSFWorkbook
     * @author shizhenwei5
     * @date 2020年3月23日
     * @param data 导出数据
     * @param fields 导出列属性
     * @param fieldTypes 导出列属性类型
     * @param template 导出模板流
     * @param rowNum 模板第几行导出
     * @return
     * @throws IOException
     */
    public static XSSFWorkbook getXSSFWorkbook(Object data, String[] fields,String[] fieldTypes, InputStream template,Integer rowNum) throws IOException {
        JSONArray jsonData = (JSONArray) JSONArray.toJSON(data);
        XSSFWorkbook workbook = new XSSFWorkbook(template);
        XSSFSheet sheet = workbook.getSheetAt(0);
        int startRowIndex;
        if(null != rowNum) {
            startRowIndex = rowNum>0?rowNum-1:0;
        }else {
            startRowIndex = 0;
            while(true) {
                XSSFRow row = sheet.getRow(startRowIndex);
                if(row==null || null==row.getCell(0) || StringUtils.isEmpty(row.getCell(0).getRawValue())) {
                    break;
                }
                startRowIndex++;
            }
        }

        for (int i = 0; i < jsonData.size(); i++, startRowIndex++) {
            JSONObject jsonObj = jsonData.getJSONObject(i);
            for (int colIndex = 0; colIndex < fields.length; colIndex++) {
                XSSFCell tempCell = getXssfCell(sheet, startRowIndex, colIndex, true);
                if(null==jsonObj.get(fields[colIndex])) {
                    continue;
                }
                if(null == fieldTypes) {
                    tempCell.setCellValue(jsonObj.getString(fields[colIndex]));
                    continue;
                }
                
                if("Integer".equals(fieldTypes[colIndex]) || "int".equals(fieldTypes[colIndex])) {
                    tempCell.setCellValue(jsonObj.getInteger(fields[colIndex]));
                }else if("Long".equals(fieldTypes[colIndex]) || "long".equals(fieldTypes[colIndex])) {
                    tempCell.setCellValue(jsonObj.getLong(fields[colIndex]));
                }else if("Double".equals(fieldTypes[colIndex]) || "double".equals(fieldTypes[colIndex])) {
                    tempCell.setCellValue(jsonObj.getDouble(fields[colIndex]));
                }else if("Float".equals(fieldTypes[colIndex]) || "float".equals(fieldTypes[colIndex])) {
                    tempCell.setCellValue(jsonObj.getFloat(fields[colIndex]));
                }else if("BigDecimal".equals(fieldTypes[colIndex])){
                    tempCell.setCellValue(jsonObj.getLong(fields[colIndex]));
                } if("Date".equals(fieldTypes[colIndex])) {
                    Date cellDate = jsonObj.getDate(fields[colIndex]);
                    //tempCell.setCellType(CellType.STRING);
                    if(null != cellDate) {
                        tempCell.setCellValue(DateTimeUtils.getDate(cellDate));
                    }
                }else {
                    tempCell.setCellValue(jsonObj.getString(fields[colIndex]));
                }
            }
        }
        return workbook;
    }

    /**
     * 描述:创建或获取单元格
     * @author shizhenwei5
     * @date 2020年3月20日
     * @param sheet
     * @param rowIndex
     * @param colIndex
     * @param isCreate
     * @return
     */
    public static XSSFCell getXssfCell(XSSFSheet sheet, int rowIndex, int colIndex, boolean isCreate) {
        if (isCreate) {
            XSSFRow row = sheet.getRow(rowIndex);
            if (row == null) {
                row = sheet.createRow(rowIndex);
                row.setHeightInPoints(24);// 设置行的高度(单元格的高度)
            }
            XSSFCell cell = row.getCell(colIndex);
            if (cell == null) {
                cell = row.createCell(colIndex);
            }
            return cell;
        } else {
            return getXssfCell(sheet, rowIndex, colIndex);
        }
    }

    /**
     * 描述:获取 不创建单元格
     * @author shizhenwei5
     * @date 2020年3月20日
     * @param sheet
     * @param rowIndex
     * @param colIndex
     * @return
     */
    public static XSSFCell getXssfCell(XSSFSheet sheet, int rowIndex, int colIndex) {
        XSSFRow row = sheet.getRow(rowIndex);
        if (row != null) {
            XSSFCell cell = row.getCell(colIndex);
            if (cell != null) {
                return cell;
            }
        }
        return null;
    }
}

猜你喜欢

转载自www.cnblogs.com/zwcry/p/12552082.html