POI导入导出

/**
* @Author: ycw
* @Description: 导入导出excel工具类
* @DateTime: 2021/9/17 10:43
**/
public class ExcelUtils {

    //文件存放位置
    private static final String FILE_PATH= "d:/tmp";

    public static void main(String[] args) {
        int columnNumber = 6;
        int[] columnWidth = {20, 20, 20, 20, 20, 20};
        String titleName = "测试";
        String[] columnName = {"评审项目", "评审要点", "分值", "评审方法", "评审结果及扣分原因", "得分"};
        String[][] dataList= {{"物理安全","二", "三1","四1", "五1", "六1"},
                {"物理安全","二", "三1","四2", "五2", "六2"},
                {"物理安全","二", "三","四3", "五3", "六3"}};
        try {
            //导出数据并合并上下相同的单元格
            String s = exportExcelAndMerge(columnNumber, columnWidth, titleName, columnName, dataList);
            //导出数据
            String s1 = exportExcelAndMerge(columnNumber, columnWidth, titleName, columnName, dataList);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    /**
     * 获取excel中的数据,指定开始行,可选着指定结束行
     * @param fileInputStream 			excel文件输入流
     * @param beginRow		取数数据的开始行
     * @param endRow		取数数据的结束行 ,不指定传入0
     * @param endColl		结束列
     * @return 以二位数组的形式返回所有数据
     * @throws Exception
     */
    public static List<String[]> getExcel(FileInputStream fileInputStream, int beginRow, int endRow, int endColl) throws Exception{
        List<String[]> list = new ArrayList<String[]>();
        //2013版及之前的HSSFWorkbook 2017版本用XSSFWorkbook
        XSSFWorkbook wb = new XSSFWorkbook(fileInputStream);
        XSSFSheet sheet = wb.getSheetAt(0);
        if(endRow == 0 ) {
            endRow = sheet.getLastRowNum();
        }
        for (int i = beginRow; i <= endRow; i++) {
            XSSFRow row = sheet.getRow(i);
            String[] cells = new String[endColl];
            for (int j = 0; j < endColl; j++) {
                XSSFCell cell = row.getCell(j);
                try {
                    int type = cell.getCellType();
                    if(type==1) {
                        cells[j] = cell.getStringCellValue();
                    }else if(type==0) {
                        cells[j] = String.valueOf(cell.getNumericCellValue());
                        if(cells[j].substring(cells[j].length()-2, cells[j].length()).equals(".0")) {
                            cells[j] = cells[j].substring(0,cells[j].length()-2);
                        }
                    }else {
                        cells[j] = "";
                    }
                } catch (Exception e) {
                    cells[j] = "";
                }

            }
            list.add(cells);
        }
        fileInputStream.close();
        return list;
    }

    /**
     * 获取excel中的数据,指定开始行,结束行,指定列
     * @param fileInputStream 			excel文件输入流
     * @param columnNumber	int[]需要取的列的序号
     * @param beginRow		取数数据的开始行
     * @param endRow		指定取数数据的结束行 ,不指定则出入0
     * @return
     * @throws Exception
     */
    public static List<String[]> getExcel(FileInputStream fileInputStream,int[] columnNumber,int beginRow,int endRow) throws Exception{
        List<String[]> list = new ArrayList<String[]>();
        HSSFWorkbook wb = new HSSFWorkbook(fileInputStream);
        HSSFSheet sheet = wb.getSheetAt(0);
        if(endRow == 0 ) {
            endRow = sheet.getLastRowNum();
        }

        for (int i = beginRow; i <= endRow; i++) {
            HSSFRow row = sheet.getRow(i);
            String[] cells = new String[columnNumber.length];
            for (int j = 0; j < columnNumber.length; j++) {
                HSSFCell cell = row.getCell(columnNumber[j]);
                try {
                    int type = cell.getCellType();
                    if(type==1) {
                        cells[j] = cell.getStringCellValue();
                    }else if(type==0) {
                        cells[j] = String.valueOf(cell.getNumericCellValue());
                        if(cells[j].substring(cells[j].length()-2, cells[j].length()).equals(".0")) {
                            cells[j] = cells[j].substring(0,cells[j].length()-2);
                        }
                    }else {
                        cells[j] = "";
                    }
                } catch (Exception e) {
                    cells[j] = "";
                }
            }


            list.add(cells);
        }
        return list;
    }
    /**
     * 导出数据成excel
     * @param columnNumber 	列数量
     * @param columnWidth	各列宽
     * @param titleName		标题
     * @param columnName	各列名
     * @param dataList		数据
     * @return
     */
    public static String ExportExcel(Integer columnNumber,int[] columnWidth,String titleName,String[] columnName,String[][] dataList) throws Exception{
        // 第一步,创建一个webbook,对应一个Excel文件
        HSSFWorkbook wb = new HSSFWorkbook();

        // 第二步,在webbook中添加一个sheet,对应Excel文件中的sheet
        HSSFSheet sheet = wb.createSheet("sheetname");

        for (int i = 0; i < columnNumber; i++){
            sheet.setColumnWidth(i, columnWidth[i] * 270); // 单独设置每列的宽
        }

        // 第三步 , 创建第0行 也就是标题
        HSSFRow row1 = sheet.createRow((int) 0);
        row1.setHeightInPoints(45); // 设备标题的高度
        //创建标题的单元格样式style2以及字体样式
        HSSFFont fontStyle2 = getFontStyle(wb, true, "宋体", (short)15);
        HSSFCellStyle style2 = getHeadCellStyle(wb, fontStyle2);
        // 创建标题第一列
        HSSFCell cell1 = row1.createCell(0);
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, columnNumber - 1)); // 合并第0到第11列
        cell1.setCellValue(titleName); // 设置值标题
        cell1.setCellStyle(style2); // 设置标题样式



        // 创建第1行 也就是表头
        HSSFRow row = sheet.createRow((int) 1);
        row.setHeightInPoints(37);// 设置表头高度
        //设置表头单元格样式以及字体样式
        HSSFFont fontStyle = getFontStyle(wb, true, "宋体", (short)13);
        HSSFCellStyle style = getHeadCellStyle(wb, fontStyle);
        //创建表头的列
        for (int i = 0; i < columnNumber; i++){
            HSSFCell cell = row.createCell(i);
            cell.setCellValue(columnName[i]);
            cell.setCellStyle(style);
        }

        //创建数据单元格样式 :自动换行 ,上下/左右居
        HSSFCellStyle cellStyle = getCellStyle(wb, null);
        //创建单元格,并设置值
        for(int i = 0; i < dataList.length; i++){
            row = sheet.createRow((int) i + 2);
            row.setHeightInPoints(20);//行高
            HSSFCell datacell = null;
            for (int j = 0; j < columnNumber; j++){
                datacell = row.createCell(j);
                datacell.setCellValue(dataList[i][j]);
                datacell.setCellStyle(cellStyle);
            }
        }


        // 第五步,将文件存到指定位置
        String filePath = saveFile(wb,titleName);
        return filePath;
    }


    /**
     * 导出数据成excel,并合并上下相同的单元格
     * @param columnNumber 	列数量
     * @param columnWidth	各列宽
     * @param titleName		标题
     * @param columnName	各列名
     * @param dataList		数据
     * @return
     */

    public static String exportExcelAndMerge(int columnNumber,int[] columnWidth,String titleName,String[] columnName,Object[][] dataList) throws Exception{
        // 第一步,创建一个webbook,对应一个Excel文件
        HSSFWorkbook wb = new HSSFWorkbook();

        // 第二步,在webbook中添加一个sheet,对应Excel文件中的sheet
        HSSFSheet sheet = wb.createSheet("sheetName");

        for (int i = 0; i < columnNumber; i++){
            sheet.setColumnWidth(i, columnWidth[i] * 270); // 单独设置每列的宽
        }

        // 第三步 , 创建第0行 也就是标题
        HSSFRow row1 = sheet.createRow(0);
        row1.setHeightInPoints(45); // 设备标题的高度
        //创建标题的单元格样式style2以及字体样式
        HSSFFont fontStyle2 = getFontStyle(wb, true, "宋体", (short)15);
        HSSFCellStyle style2 = getHeadCellStyle(wb, fontStyle2);
        // 创建标题第一列
        HSSFCell cell1 = row1.createCell(0);
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, columnNumber - 1)); // 合并第0到第11列
        cell1.setCellValue(titleName); // 设置值标题
        cell1.setCellStyle(style2); // 设置标题样式



        // 创建第1行 也就是表头
        HSSFRow row = sheet.createRow((int) 1);
        row.setHeightInPoints(37);// 设置表头高度
        //设置表头单元格样式以及字体样式
        HSSFFont fontStyle = getFontStyle(wb, true, "宋体", (short)13);
        HSSFCellStyle style = getHeadCellStyle(wb, fontStyle);
        //创建表头的列
        for (int i = 0; i < columnNumber; i++){
            HSSFCell cell = row.createCell(i);
            cell.setCellValue(columnName[i]);
            cell.setCellStyle(style);
        }

        //创建数据单元格样式 :自动换行 ,上下/左右居
        HSSFCellStyle cellStyle = getCellStyle(wb, null);
        int[] k = new int[columnNumber];
        //创建单元格,并设置值
        for(int i = 0; i < dataList.length; i++){

            row = sheet.createRow((int) i + 2);
            row.setHeightInPoints(20);//行高
            HSSFCell datacell = null;
            for (int j = 0; j < columnNumber; j++){
                datacell = row.createCell(j);
                datacell.setCellValue((String) dataList[i][j]);
                datacell.setCellStyle(cellStyle);



                //合并上下相同的单元格
                if(i != 0){
                    boolean isEquel =  dataList[i][j].equals(dataList[i-1][j]) &&  (! "".equals(dataList[i][j]));
                    if (isEquel) {//上下相同时,该列数量+1
                        k[j] = k[j]+1;
                    }else{//上下不相同
                        if(k[j] > 0){//该列之前有相同的,进行合并,并将相同数初始化为0
                            sheet.addMergedRegion(new CellRangeAddress(i+2-k[j]-1, i+2-1, j, j));
                            k[j] = 0;
                        }
                    }

                    //到最后一,判断是否有相同的,进行合并
                    if (i == dataList.length-1 ){
                        if(k[j] > 0){
                            sheet.addMergedRegion(new CellRangeAddress(i+2-k[j], i+2, j, j));
                            k[j] = 0;
                        }
                    }
                }

            }


        }

        // 第五步,将文件存到指定位置
        String filePath = saveFile(wb,titleName);
        return filePath;
    }

    /**
     * 标题单元格样式
     * @param wb		HSSFWorkbook 对象
     * @param font		HSSFFont字体样式
     * @return
     */
    private static HSSFCellStyle getHeadCellStyle(HSSFWorkbook wb, HSSFFont font) {
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        style.setBottomBorderColor(HSSFColor.BLACK.index);
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);

        if(font!=null) {
            style.setFont(font);
        }
        return style;
    }
    /**
     * 数据单元格样式
     * @param wb
     * @param font
     * @return
     */
    private static HSSFCellStyle getCellStyle(HSSFWorkbook wb, HSSFFont font) {
        HSSFCellStyle style = wb.createCellStyle();
        style.setWrapText(true);// 设置自动换行
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 创建一个上下居中格式
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中
        // 设置边框
        style.setBottomBorderColor(HSSFColor.BLACK.index);
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);
        if(font!=null) {
            style.setFont(font);
        }
        return style;
    }

    /**
     * 获得字体样式
     * @param wb HSSFWorkbook对象
     * @param bold		是否粗体
     * @param fontName	字体类型
     * @param fontSize	字体大小
     * @return
     */
    private static HSSFFont getFontStyle(HSSFWorkbook wb, boolean bold, String fontName, short fontSize) {
        HSSFFont headerFont = (HSSFFont) wb.createFont(); // 创建字体样式
        if(bold) {
            headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 字体加粗
        }
        headerFont.setFontName(fontName); // 设置字体类型
        headerFont.setFontHeightInPoints(fontSize); // 设置字体大小
        return headerFont;
    }
    /**
     * 保存文件
     * @param wb
     * @param fileName
     * @return
     */
    private static String saveFile(HSSFWorkbook wb, String fileName) throws Exception {
        String filePath="";
        //根据如期生成文件相对路径
        Date createTime = new Date();
        SimpleDateFormat forMater = new SimpleDateFormat("yyyyMMdd");
        String path = "export" + File.separatorChar + forMater.format(createTime);

        File targetFile = new File(FILE_PATH + File.separatorChar, path);
        //判断文件夹是否存在,不存在则创建
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }

        //生成文件名
        //文件存放路劲
        String fileStr = FILE_PATH + File.separatorChar + path + File.separatorChar +fileName;
        filePath = fileStr+ ".xls";
        File file=new File(filePath);
        int i=1;
        //判断文件是否存在,存在则文件名称加序号
        while(file.exists()) {
            filePath=fileStr+i+".xls";
            file=new File(filePath);
            i++;
        }
        FileOutputStream fout = new FileOutputStream(file);
        wb.write(fout);
        String str = "导出" + filePath + "成功!";
        fout.close();
        return filePath;
    }
}

public class ListToTwoArray {
    /**
     *
     *@Title:  ListToArray
     *@Description: list列表转换成二维数组
     *@Author: ycw
     *@Since: 2021年9月17日下午2:01:25
     *@param: @param list
     *@param: @param keyLength每行的列数,按最长的计算
     *@param: @return
     *@return Object[][]
     */
    public static Object[][] ListToArray(List<LinkedHashMap<String, Object>> listMap, int keyLength) {
        if (CollectionUtils.isEmpty(listMap)) {
            return new Object[0][];
        }
        int size = listMap.size();
        Object[][] array = new Object[size][keyLength];
        //将listMap转换为list<list>
        List<List<String>> listList = new LinkedList<>();
        for (LinkedHashMap<String, Object> linkedHashMap : listMap) {
            List<String> list = new LinkedList<>();
            for (Map.Entry entryMap : linkedHashMap.entrySet()) {
                list.add(entryMap.getValue().toString());
            }
            listList.add(list);
        }
        //二维数组填数据
        try {
            for (int i = 0; i < size; i++) {
                for (int j = 0; j <keyLength ; j++) {
                    array[i][j] = listList.get(i).get(j);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(Arrays.deepToString(array));
        return array;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值