POI导出excel文件样式

需求:

  公司业务和银行挂钩,各种形式的数据之间交互性比较强,这就涉及到了存储形式之间的转换

  比如数据库数据与excel文件之间的转换


解决:

  我目前使用过的是POI转换数据库和文件之间的数据,下边上代码

package org.triber.portal.model.area;

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class AreaExcelUtil {

    /**
     * 导出excel
     * @param tableTileCH 表中文字段数组
     * @param fileName 文件全路径名
     * @param list 数据集
     * @param tableTileEN 映射字段集
     */
    public void exportExcel (String[] tableTileCH, String fileName, List<?> list, String[] tableTileEN){
        //文件不存在则创建文件
        File file=new File(fileName);
        if(!file.exists())
        {
            try {
                file.createNewFile();
            } catch (IOException e) {
                System.out.println("failed to create file.");
                e.printStackTrace();
            }
        }
        OutputStream out= null;
        try {
            out = new FileOutputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();

        }
        //创建工作簿
        HSSFWorkbook workbook=new HSSFWorkbook();
        HSSFFont f=workbook.createFont();
        f.setBold(true);
        f.setFontName("宋体");
        f.setColor((short)100);
        HSSFCellStyle style = workbook.createCellStyle();
        // 设置这些样式
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);//水平居中
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//垂直居中
        // 背景色
        style.setFillForegroundColor(HSSFColor.YELLOW.index);
        style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        style.setFillBackgroundColor(HSSFColor.YELLOW.index);
        // 设置边框
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);
        // 自动换行
        style.setWrapText(true);
        HSSFSheet sheet=workbook.createSheet("shoot1");
        sheet.setDefaultColumnWidth((short) 15); //这里很关键,不设置这里导出的列宽窄,数据不正确
        /**
         * 写入数据
         */
        HSSFRow row=sheet.createRow(0);//创建一行
        row.setRowStyle(style);
        String str = "";
        //生成列名
        for (int i = 0; i < tableTileCH.length; i++) {
            //excel的格子单元 一行
            HSSFCell cell = row.createCell(i);
            cell.setCellValue(tableTileCH[i]);
        }
        //生成列值
        for (int i = 0; i < list.size(); i++) {
            HSSFRow dataRow = sheet.createRow(i + 1);
            for (int m = 0; m < tableTileCH.length; m++) {
                Map<String, Object> map = (Map<String, Object>) list.get(i);
                HSSFCell dataCell = dataRow.createCell(m);
                str = String.valueOf(
                        map.get(tableTileEN[m])) == null ? "": String.valueOf(map.get(tableTileEN[m]));
                str = str.equals("null") ? "" : str;
                dataCell.setCellValue(str);
            }
        }
        //写文件
        try {
            workbook.write(out);
        } catch (IOException e) {
            e.printStackTrace();
        } finally{
            try {
                //关闭流
                out.flush();
                out.close();
                workbook.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * 从Excel此向数据库导入数据
     */
    public List<Area> importExcel(FileInputStream fileInputStream) {
        List<Area> list = new ArrayList<Area>();
        try {
            //创建Excel工作薄
            HSSFWorkbook hwb = new HSSFWorkbook(fileInputStream);
            //得到第一个工作表
            HSSFSheet sheet = hwb.getSheetAt(0);
            HSSFRow row = null;
            //表示工作表的总数
            for(int i = 0; i < hwb.getNumberOfSheets(); i++){
                sheet = hwb.getSheetAt(i);
                //行数
                for(int j = 1; j < sheet.getLastRowNum(); j++){
                    row = sheet.getRow(j);
                    Area area = new Area();
                    HSSFCell areaId = row.getCell(0);
                    area.setAreaId(getCellValue(areaId));
                    HSSFCell areaDscr = row.getCell(1);
                    area.setAreaDscr(getCellValue(areaDscr));
                    HSSFCell level = row.getCell(2);
                    area.setLevel(getCellValue(level));
                    HSSFCell beginTime = row.getCell(3);
                    area.setBeginTime(getCellValue(beginTime));
                    HSSFCell closeTime = row.getCell(4);
                    area.setCloseTime(getCellValue(closeTime));
                    HSSFCell entryDis = row.getCell(5);
                    if("是".equals(getCellValue(entryDis) )){
                        area.setEntryDis("1");
                    }else {  area.setEntryDis("0");}
                    HSSFCell entryCode = row.getCell(6);
                    area.setEntryCode(getCellValue(entryCode));
                    HSSFCell oldCode = row.getCell(7);
                    area.setOldCode(getCellValue(oldCode));
                    HSSFCell oldId = row.getCell(8);
                    area.setOldId(getCellValue(oldId));
                    HSSFCell reviseTime = row.getCell(9);
                    area.setReviseTime(getCellValue(reviseTime));
                    HSSFCell state = row.getCell(10);
                    area.setState(getCellValue(state));
                    HSSFCell bigCollCode = row.getCell(11);
                    area.setBigCollCode(getCellValue(bigCollCode));
                    //生成结果集
                    list.add(area);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 判断从Excel文件中解析出来数据的格式
     * @param cell 待解析的单元格
     * @return 字符串
     */
    private static String getCellValue(HSSFCell cell){

        String value = null;
        if(null!=cell) {
            switch (cell.getCellType()) {
                //字符串
                case HSSFCell.CELL_TYPE_STRING: {
                    value = cell.getRichStringCellValue().getString();
                    break;
                }
                //数字
                case HSSFCell.CELL_TYPE_NUMERIC: {
                    if (HSSFDateUtil.isCellDateFormatted(cell)) {
                        //如果是date类型则 ,获取该cell的date值
                        Date date = HSSFDateUtil.getJavaDate(cell.getNumericCellValue());
                        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        value = format.format(date);
                    } else {
                        long dd = (long) cell.getNumericCellValue();
                        value = dd + "";
                    }
                    break;
                }
                case HSSFCell.CELL_TYPE_BLANK: {
                    value = "";
                    break;
                }
                case HSSFCell.CELL_TYPE_FORMULA: {
                    value = String.valueOf(cell.getCellFormula());
                    break;
                }
                //boolean型值
                case HSSFCell.CELL_TYPE_BOOLEAN: {
                    value = String.valueOf(cell.getBooleanCellValue());
                    break;
                }
                case HSSFCell.CELL_TYPE_ERROR: {
                    value = String.valueOf(cell.getErrorCellValue());
                    break;
                }
                default:
                    break;
            }
        }
        return value;
    }
}

总结:

  以上就是POI导入导出的相关代码,亲测可用!

  

原文地址:https://www.cnblogs.com/hackxiyu/p/8309266.html