POI生成Excel文件/POI读取Excel文件

来源:互联网 发布:电摩淘宝网 编辑:程序博客网 时间:2024/05/14 22:40
package com.ultrapower.gcos.common;


import com.ultrapower.gcos.entity.app.AppManage;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;


import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;


public class ExcelUtil {


    private Logger logger = LoggerFactory.getLogger(this.getClass());


    public static final int SHEET_SIZE = 50000;


    private static final String SUB_FILE = "\\.";


    private static final String BIG_SPLIT = "_";


    private static final String STR_EMP = "";


    private static final int COL_WIDTH = 15;


    private static final String[] HEADERS = {"应用ID","应用名称","别名","路径","应用类型","应用状态","描述"};


    /*生成excel文件*/
    //filePath获取方式 request.getSession().getServletContext().getRealPath("/").concat("/xxx").concat(".xls")
    public int invokExportExcel(List<String[]> datalist, String filePath){
        int result = ExportExcel(datalist, filePath, SHEET_SIZE, "big", true);
        return result;
    }


    /*导入*/
    public List<AppManage> invokImportExcel(MultipartFile filePath) throws Exception {
        InputStream is = filePath.getInputStream();
        List<AppManage> data = importFromExcel(is);
        return data;
    }


    /**
     * 数据导出
     * @param datalist
     * @param filePath
     * @param sheetMaxSize
     * @param mode
     * @param compress
     * @return
     */
    private int ExportExcel(List<String[]> datalist, String filePath, int sheetMaxSize, String mode, boolean compress) {
        try {
            filePath = filePath.replaceAll("\\\\", "/");
            int endCom = filePath.lastIndexOf("/");
            int fileCount = 1;


            if (sheetMaxSize < 2 || sheetMaxSize > 65535) {
                sheetMaxSize = SHEET_SIZE;
            }


            // 文件路径
            List<String> file_path_s = new ArrayList<String>();


            // 路径
            String path = filePath.substring(0, endCom);


            // 文件名
            String filename = filePath.substring(endCom + 1, filePath.length());
            String baseName = filename.split(SUB_FILE)[0];
            String expName = filename.split(SUB_FILE).length > 1 ? filename.split(SUB_FILE)[1] : STR_EMP;
            if ("big".equals(mode)) {
                filePath = path + File.separator + baseName + BIG_SPLIT + fileCount + "." + expName;
            }


            //创建导出Excel存放路径
            path = this.createFolder(path);


            //这边导出的文件是按当前毫秒值命名的, 并且是最多导出10条记录
            //申明一个工作薄
            HSSFWorkbook workbook = null;
            //创建可以写入的工作表
            HSSFSheet sheet = null;
            //导出的数据
            List<String[]> dataList = null;
            //分类数据
            Map<String, List<String[]>> data = null;
            List<String[]> typeList = null;


            if(datalist != null && datalist != null && !datalist.isEmpty()){
                data = new HashMap<String, List<String[]>>();//String--sheet标题; list所有的数据集合
                dataList = datalist;
                data.put("app信息", dataList);
                //文件名取得当前时间毫秒值
                File excelFile = new File(filePath);
                if(!excelFile.exists()){
                    file_path_s.add(filePath);
                    workbook = new HSSFWorkbook();
                    HSSFCellStyle style = this.getHeaderStyle(workbook);
                    HSSFCellStyle dataStyle = getDataStyle(workbook);
                    //循环创建sheet页
                    for(String typeName : data.keySet()){
                        //定义sheet页的标题名称
                        sheet = workbook.createSheet(typeName);
                        typeList = data.get(typeName);
                        //写入列名
                        HSSFRow row = sheet.createRow(0);
                        row.setHeight((short) 600);
                        HSSFCell cell = null;
                        String[] hears = HEADERS;
                        for(int i = 0; i < hears.length; i++) {
                            sheet.setColumnWidth(i, (short)(35.7*180));
                            cell = row.createCell(i);
                            cell.setCellStyle(style);
                            //根据国际化信息设置对应的列名
                            cell.setCellValue(hears[i]);
                        }
                        //写入数据
                        for(int i=1; i<typeList.size()+1; i++){
                            row = sheet.createRow(i);
                            row.setHeight((short)(15.625*25));
                            String[] str = typeList.get(i-1);
                            for(int j=0; j<str.length; j++){
                                cell = row.createCell(j);
                                cell.setCellStyle(dataStyle);
                                cell.setCellValue(new HSSFRichTextString(str[j]));
                            }
                        }
                    }
                }
            }
            FileOutputStream fos = new FileOutputStream(filePath);
            workbook.write(fos);
            fos.flush();
            fos.close();
            if (compress) {
                zip(file_path_s, path + File.separator + baseName + ".zip");
            }
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }


    private HSSFCellStyle getHeaderStyle(HSSFWorkbook workbook) {
        // 生成一个样式
        HSSFCellStyle style = workbook.createCellStyle();
        // 设置这些样式
        style.setFillForegroundColor(HSSFColor.ROYAL_BLUE.index);
        style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        // 生成一个字体
        HSSFFont font = workbook.createFont();
        font.setFontHeightInPoints((short)10.5);
        font.setColor(HSSFColor.WHITE.index);
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        // 把字体应用到当前的样式
        style.setFont(font);


        return style;
    }


    private static HSSFCellStyle getDataStyle(HSSFWorkbook workbook) {
        // 生成一个样式
        HSSFCellStyle style = workbook.createCellStyle();
        // 设置这些样式
        style.setFillForegroundColor(HSSFColor.WHITE.index);
        style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        // 生成一个字体
        HSSFFont font = workbook.createFont();
        font.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
        // 把字体应用到当前的样式
        style.setFont(font);


        return style;
    }


    private String createFolder(String path) {
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        return path;
    }


    private void zip(List<String> filepaths, String zipFileName) throws Exception {
        File file = new File(zipFileName);
        if (!file.exists()) {
            file.createNewFile();
        }
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName));
        for (int i = 0; i < filepaths.size(); i++) {
            File f = new File(filepaths.get(i));
            out.putNextEntry(new ZipEntry(f.getName()));
            FileInputStream in = new FileInputStream(f);
            int b;
            while ((b = in.read()) != -1) {
                out.write(b);
            }
            in.close();


            this.deleteFile(filepaths.get(i));
        }
        out.flush();
        out.finish();
        out.close();
    }


    private boolean deleteFile(String filepath) throws Exception {
        File file = new File(filepath);
        return file.delete();
    }


    /**
     * 数据导入
     * @param is
     * @return
     * @throws IOException
     */
    private List<AppManage> importFromExcel(InputStream is) throws IOException {
        HSSFWorkbook wb = new HSSFWorkbook(is);
        HSSFSheet sheet = wb.getSheetAt(0);
        String sheetName = sheet.getSheetName();
        logger.debug("sheet页名称====="+sheetName);
        if(!"app信息".equals(sheetName)){
            sheet = wb.getSheetAt(1);
        }
        List<AppManage> data = new ArrayList<AppManage>();
        // 获取第一行的数据
        int rowbegin = 1;
        Row exrow = sheet.getRow(0);


        int LastRowNum = 0;
        int begin = sheet.getFirstRowNum();
        int end = sheet.getLastRowNum();
        for (int i = begin; i <= end; i++) {
            if (null == sheet.getRow(i)) {
                break;
            }
            LastRowNum++;
        }
        if (exrow != null) {
            Cell excell = exrow.getCell(0);
            String ex_excelTopValue = excell.getStringCellValue();
            // 如果单元格数据为(应用ID)循环从这里开始
            if("应用ID".equals(ex_excelTopValue)){
                rowbegin=1;
            }else{
                rowbegin=2;
            }
        }
        try {
            // 行
            for (int r = rowbegin ; r <= LastRowNum ; r++) {
                HSSFRow row = sheet.getRow(r);


                if (row == null) {
                    continue;
                }


                AppManage app = new AppManage();
                // 列值
                app.setAppName(getValue(row.getCell(0)));
                app.setAppAlias(getValue(row.getCell(1)));
                app.setAppPath(getValue(row.getCell(2)));
                app.setAppType(getValue(row.getCell(3)));
                app.setAppEnable("启用".equals(getValue(row.getCell(4))) == true ? "1" : "0");
                app.setAppDescription(getValue(row.getCell(5)));
                if(app != null && app.getAppName() != "") {
                    data.add(app);
                }
            }
        } finally {
            is.close();
        }
        return data;
    }


    private String getValue(HSSFCell cell) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String value = "";
        if (cell == null) {
            value = "";
        } else {
            switch(cell.getCellType()) {
                case HSSFCell.CELL_TYPE_STRING:
                    value = cell.getStringCellValue();
                    break;
                case HSSFCell.CELL_TYPE_BOOLEAN:
                    value = ""+cell.getBooleanCellValue();
                    break;
                case HSSFCell.CELL_TYPE_NUMERIC:
                    if (org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(cell)) {
                        value = sdf.format(cell.getDateCellValue());
                    } else {
                        value = ""+cell.getNumericCellValue();
                    }
                    break;
                case HSSFCell.CELL_TYPE_FORMULA:
                    value = cell.getCellFormula();
                    break;
                case HSSFCell.CELL_TYPE_BLANK:
                    value = "";
                    break;
                default:
                    value = "";
                    break;
            }
        }
        return value;
    }


}
原创粉丝点击