Java++:POI 導入|導出 工具類(一)

沒有十全十美的程序


 1、封裝工具類

package com.osrmt.util;

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Excel處理工具類
 *
 */
public class ExcelUtil {

    /**
     * 導出excel
     * @param headNameList 文件字段頭顯示名字
     * @param headField 文件字段頭數據字段
     * @param listData 數據集合
     * @param stream 流
     * @throws Exception 異常
     */
    public static void exportExcel(List<String> headNameList,List<String> headField,List<Map<String,String>> listData,OutputStream stream) throws Exception{
        try (HSSFWorkbook wb = new HSSFWorkbook()) {
            HSSFSheet sheet = wb.createSheet("Sheet1");
            HSSFCellStyle titleStyle = wb.createCellStyle(); // 標題樣式
            titleStyle.setAlignment(HorizontalAlignment.CENTER);
            HSSFFont titleFont = wb.createFont(); // 創建字體樣式
            titleFont.setBold(true); // 字體加粗
            titleFont.setFontName("Times New Roman"); // 設置字體類型
            titleFont.setFontHeightInPoints((short) 18); // 設置字體大小
            titleStyle.setFont(titleFont); // 爲標題樣式設置字體樣式

            HSSFCellStyle headerXStyle = wb.createCellStyle();
            headerXStyle.setBorderTop(BorderStyle.THIN);
            headerXStyle.setBorderBottom(BorderStyle.THIN);
            headerXStyle.setBorderLeft(BorderStyle.THIN);
            headerXStyle.setBorderRight(BorderStyle.THIN);
            HSSFFont headerFont = wb.createFont(); // 創建字體樣式
            headerFont.setBold(true); // 字體加粗
            headerXStyle.setFont(headerFont);
            headerXStyle.setAlignment(HorizontalAlignment.CENTER);

            //獲取表頭顯示名稱
            String[] titles = new String[headNameList.size()];
            for (int i = 0; i < headNameList.size(); i++) {
                titles[i] = headNameList.get(i);
            }

            int rowInd = 0;
            HSSFRow headerRow = sheet.createRow(rowInd);
            headerRow.setHeightInPoints(16);
            for (int i = 0; i < titles.length; i++) {
                HSSFCell cell = headerRow.createCell(i);
                cell.setCellValue(titles[i]);
                cell.setCellStyle(headerXStyle);
            }

            HSSFCellStyle headerCStyle = wb.createCellStyle();
            headerCStyle.setBorderTop(BorderStyle.THIN);
            headerCStyle.setBorderBottom(BorderStyle.THIN);
            headerCStyle.setBorderLeft(BorderStyle.THIN);
            headerCStyle.setBorderRight(BorderStyle.THIN);

            titles = new String[headField.size()];
            for (int i = 0; i < headField.size(); i++) {

                titles[i] = headField.get(i).toLowerCase();
            }
            if (listData != null) {
                for (Map<String, String> map : listData) {
                    rowInd++;
                    HSSFRow _row = sheet.createRow(rowInd);
                    _row.setHeightInPoints(16);

                    for (int j = 0; j < titles.length; j++) {
                        HSSFCell cell = _row.createCell(j);
                        cell.setCellStyle(headerCStyle);

                        cell.setCellValue(StringUtil.toNotNullString(map.get(titles[j])));
                    }
                }
            }
            wb.write(stream);

            /*OutputStream out = new FileOutputStream("F:/" + "xls.xlsx");
            wb.write(out);*/
        }
    }
    
    /**
     * 檢查導入excel字段頭格式是否正確
     * @param wb 工作簿
     * @param colName 列名列表
     * @return 是:一致
     */
    public static boolean checkFormat(HSSFWorkbook wb,List<String> colName) {
        HSSFSheet sheet=wb.getSheetAt(0);
        int lastRow = sheet.getLastRowNum();
        if (lastRow <1) {
            return false;
        }
        //檢查格式,表頭是否一致
        Row row = sheet.getRow(0);
        int cellF = row.getFirstCellNum();
        int cellL = row.getLastCellNum();
        if (cellF >= 0 && cellL >= colName.size()) {
            for(int i=0;i<cellL;i++){
                String xlsColString=row.getCell(i).getStringCellValue();
                String colString=colName.get(i);
                if (!xlsColString.equals(colString)) {
                    return false;
                }
            }
            return true;
        }
        return false;
    }
    
    /**
     * 解析excel數據
     * @param wb excel文件對象
     * @param headNameList 文件字段頭顯示名字
     * @param headFieldList 文件字段頭數據字段
     * @return 數據集合
     */
    public static List<Map<String,Object>> analysisExcel(HSSFWorkbook wb,List<String> headNameList,List<String> headFieldList) {
        HSSFSheet sheet=wb.getSheetAt(0);
        int lastRow = sheet.getLastRowNum();
        List<Map<String, Object>> list = new ArrayList<>();
        for (int i = lastRow; i >= 1; i--) {
            Row row = sheet.getRow(i);
            if (row == null) {
                continue;
            }
            int firstCell = row.getFirstCellNum();
            int lastCell = row.getLastCellNum();
            if (firstCell != 0 &&lastCell > headNameList.size()) {
                continue;
            }
            Map<String, Object> map = new HashMap<>();
            for (int j = firstCell; j < lastCell; j++) {
                Cell cell = row.getCell(j);
                    if (cell == null) {
                    continue;
                }
                CellType style = cell.getCellTypeEnum();
                String cellString = "";
                if (style == CellType.BOOLEAN) {
                    cellString = String.valueOf(row.getCell(j).getBooleanCellValue());
                } else if (style == CellType.NUMERIC) {
                    short format = cell.getCellStyle().getDataFormat();
                    SimpleDateFormat sdf = null;
                    if (format == 14 || format == 31 || format == 57 || format == 58) {
                        sdf = new SimpleDateFormat("yyyy-MM-dd");
                    }else if (format == 20 || format == 32) {
                        sdf = new SimpleDateFormat("HH:mm");
                    }else if (format == 21) {
                        sdf = new SimpleDateFormat("HH:mm:ss");
                    }
                    if (sdf != null) {
                        //日期
                        double value = cell.getNumericCellValue();
                        Date date = DateUtil.getJavaDate(value);
                        cellString = StringUtil.toNotNullString(sdf.format(date));
                    }else {
                        String value = StringUtil.toNotNullString(row.getCell(j).getNumericCellValue());
                        if (value.contains(".")) {
                            //判斷是否是整形
                            String[] aa = value.split("\\.");
                            if (aa.length == 2 && aa[1].equals("0")) {
                                cellString = aa[0];
                            }else {
                                cellString = String.valueOf(row.getCell(j).getNumericCellValue());
                            }
                        }
                    }
                } else  {
                    cellString = row.getCell(j).getStringCellValue();
                }
                map.put(headFieldList.get(j), cellString);
            }
            list.add(map);
        }
        return list;
    }
}

 2,實體類:

package com.osrmt.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

@Data
@TableName(value = "xq_nenglishuxing")
public class XqNengliShuxing {
    @TableId(type= IdType.INPUT)
    @ApiModelProperty("主鍵id")
    private Long id;

    @TableField(value="code")
    @ApiModelProperty("目標編號")
    private String code;

    @TableField(value="description")
    @ApiModelProperty("能力屬性描述信息")
    private String description;

    @TableField(value="priority")
    @ApiModelProperty("優先級(0低 1中 2高)")
    private Integer priority;

    @TableField(value="is_disable")
    @ApiModelProperty("是否禁用(0啓用 1禁用)")
    private Integer isDisable;

    @TableField(value="creator")
    @ApiModelProperty("創建人")
    private String creator;

    @TableField(value = "createtime")
    @ApiModelProperty("創建時間")
    private Long createTime;

    @TableField(value="nlqd_id")
    @ApiModelProperty("所屬能力清單的id")
    private Long nlqdId;

    @TableField(value = "nengli_mubiao_value")
    @ApiModelProperty("能力目標值")
    private String nengliMubiaoValue;
}

 3,接口實現

@GetMapping("/exportExcel")
@ApiOperation("導出能力清單能力屬性excel")
public Response exportExcel(@RequestParam("nlqdId") Long nlqdId,
                   HttpServletResponse response) throws Exception {

    QueryWrapper<XqNengliShuxing> queryWrapper = new QueryWrapper<>();
    queryWrapper.lambda().eq(XqNengliShuxing::getNlqdId, nlqdId);

    List<XqNengliShuxing> list = nengliShuxingService.list(queryWrapper);


    List<Map<String, String>> data = new ArrayList<>();
    for (int i = 0; i < list.size(); i++) {
        Map<String, String> map = JSON.parseObject(JSON.toJSONString(list.get(i)), Map.class);
        data.add(map);
    }

    Properties properties = getApiModelProperty("com.osrmt.entity.XqNengliShuxing");
    List<String> headNameList = properties.values().stream().map(String::valueOf).collect(Collectors.toList());

    List<String> headFieldList = properties.keySet().stream().map(String::valueOf).collect(Collectors.toList());
    System.out.println(properties);

    try {
        ExcelUtil.exportExcel(headNameList, headFieldList, data, response.getOutputStream());
    } catch (Exception e) {
        e.printStackTrace();
        throw new Exception("導出excel失敗");
    }
    return Response.success();
}

/** 功能描述:
 * 獲取類字段ApiModelProperty註解value值(中文)
 * @param classPath: 類路徑
 * @author: zl
 * @date: 2022/2/17 17:10
 */
private Properties getApiModelProperty(String classPath){
    Properties p = new Properties();
    try {
        // 1.根據類路徑獲取類
        Class<?> c = Class.forName(classPath);
        // 2.獲取類的屬性
        Field[] declaredFields = c.getDeclaredFields();
        // 3.遍歷屬性,獲取屬性上ApiModelProperty的值,屬性的名,存入Properties
        if (declaredFields.length != 0) {
            for (Field field : declaredFields) {
                if (field.getAnnotation(ApiModelProperty.class) != null) {
                    // key和value可根據需求存
                    // 這存的key爲類屬性名,value爲註解的值
                    p.put(field.getName(), field.getAnnotation(ApiModelProperty.class).value());
                }
            }
            return p;
        }
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    return p;
}



@PostMapping("/importExcel")
@ApiOperation("導入能力清單能力屬性excel")
public Response importExcel(MultipartFile file, Long nlqdId) {
    Properties properties = getApiModelProperty("com.osrmt.entity.XqNengliShuxing");
    List<String> headNameList = properties.values().stream().map(String::valueOf).collect(Collectors.toList());
    List<String> headFieldList = properties.keySet().stream().map(String::valueOf).collect(Collectors.toList());
    try {
        HSSFWorkbook workbook =new HSSFWorkbook(new POIFSFileSystem(file.getInputStream()));
        List<Map<String, Object>> maps = ExcelUtil.analysisExcel(workbook, headNameList, headFieldList);
        for (int i = 0; i < maps.size(); i++) {
            XqNengliShuxing xqNengliShuxing = JSON.parseObject(JSON.toJSONString(maps.get(i)), XqNengliShuxing.class);
            NengliShuxingProperty nengliShuxingProperty = new NengliShuxingProperty();
            BeanUtils.copyProperties(xqNengliShuxing, nengliShuxingProperty);
            nengliShuxingProperty.setNlqdId(nlqdId);
            addNengliShuxing(nengliShuxingProperty);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return Response.success();
}

4,導出樣例:

 

感謝樓主的封裝

引文:https://www.cnblogs.com/zhulei2/p/15907855.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章