导入导出Excel文件

来源:互联网 发布:陌陌解封软件 编辑:程序博客网 时间:2024/06/05 14:24

    起先,以为实现导入导出的是js插件。后来了解到原来我大java就能操作excel文件。

    java操作excel文件还是比较简单的,不过要导入两个包(使用maven)

        <dependency>            <groupId>org.apache.poi</groupId>            <artifactId>poi</artifactId>            <version>3.9</version>        </dependency>        <dependency>            <groupId>org.apache.poi</groupId>            <artifactId>poi-ooxml</artifactId>            <version>3.9</version>        </dependency>

     需要注意的是excel 2003和excel 2007及以上的文件格式是不一样的,上段代码中poi就是操作excel 2003的HSSFWorkbook(HSSF开头), poi-ooxml是操作excel 2007及以上的XSSF开头的类。


  话不多说,直接上代码:

1. 先写个判断文件类型的工具类:

public class CEVUtil {    /**     * 依据后缀名判断读取的是否为Excel文件     * @param filePath     * @return     */    public static boolean isExcel(String filePath){        if(filePath.matches("^.+\\.(?i)(xls)$")||filePath.matches("^.+\\.(?i)(xlsx)$")){            return true;        }        return false;    }    /**     * 检查文件是否存在     */    public static boolean fileExist(String filePath){        if(filePath == null || filePath.trim().equals("")) return false;        File file = new File(filePath);        if (file == null || !file.exists()){            return false;        }        return true;    }    /**     * 依据内容判断是否为excel2003及以下     */    public static boolean isExcel2003(String filePath){        try {            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(filePath));            if(POIFSFileSystem.hasPOIFSHeader(bis)) {                System.out.println("Excel版本为excel2003及以下");                return true;            }        } catch (IOException e) {            e.printStackTrace();            return false;        }        return false;    }    /**     * 依据内容判断是否为excel2007及以上     */    public static boolean isExcel2007(String filePath){        try {            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(filePath));            if(POIXMLDocument.hasOOXMLHeader(bis)) {                System.out.println("Excel版本为excel2007及以上");                return true;            }        } catch (IOException e) {            e.printStackTrace();            return false;        }        return false;    }}

2.  操作excel的类

public class FileController {    /** 错误信息 */    private String errorInfo;    /**     * 验证EXCEL文件是否合法     */    public boolean validateExcel(String filePath){        /**判断文件名是否为空或者文件是否存在 */        if(!CEVUtil.fileExist(filePath)){            errorInfo = "文件不存在";            return false;        }        /**检查文件是否是Excel格式的文件 */        if (!CEVUtil.isExcel(filePath))  {            errorInfo = "文件名不是excel格式";            return false;        }        return true;    }    /**     * @描述:根据文件名读取excel文件     */    public List<List<String>> read(String filePath){        List<List<String>> dataLst = new ArrayList<List<String>>();        InputStream is = null;        try{            /** 验证文件是否合法 */            if (!validateExcel(filePath)){                return null;            }            /** 判断文件的类型,是2003还是2007 */            boolean isExcel2003 = true;            if (CEVUtil.isExcel2007(filePath)){                isExcel2003 = false;            }            /** 调用本类提供的根据流读取的方法 */            is = new FileInputStream(new File(filePath));            Workbook wb = null;            if (isExcel2003){                wb = new HSSFWorkbook(is);            }else{                wb = new XSSFWorkbook(is);            }            dataLst = read(wb);            is.close();        }catch (IOException e){            e.printStackTrace();        }catch (Exception ex){            ex.printStackTrace();        }finally{            if (is != null){                try{                    is.close();                }catch (IOException e){                    is = null;                    e.printStackTrace();                }            }        }        return dataLst;    }    /**     * @描述:读取数据     */    private List<List<String>> read(Workbook wb){        List<List<String>> dataLst = new ArrayList<List<String>>();        /**得到总的shell */        int sheetAccount = wb.getNumberOfSheets();        /** 得到第一个shell(第一页) */        Sheet sheet = wb.getSheetAt(0);        /** 得到Excel的行数 */        int rowCount = sheet.getPhysicalNumberOfRows();        /** 也可以通过得到最后一行数*/        int lastRowNum = sheet.getLastRowNum();        /** 循环Excel的行 */        for (int r = 0; r < rowCount; r++){            Row row = sheet.getRow(r);            if (row == null){                continue;            }            List<String> rowLst = new ArrayList<String>();            /** 循环Excel的列 */            for (int c = 0; c < row.getPhysicalNumberOfCells(); c++){                Cell cell = row.getCell(c);                String cellValue = "";                if (null != cell){                    // 以下是判断数据的类型                    switch (cell.getCellType()){                        //XSSFCell可以达到相同的效果                        case HSSFCell.CELL_TYPE_NUMERIC: // 数字                            double d = cell.getNumericCellValue();                            if (HSSFDateUtil.isCellDateFormatted(cell)) {//日期类型                                // Date date = cell.getDateCellValue();                                Date date = HSSFDateUtil.getJavaDate(d);                                cellValue =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);                            }else{//数值类型                                cellValue = cell.getNumericCellValue()+"";                            }                            cellValue = cell.getDateCellValue() + "";                            break;                        case HSSFCell.CELL_TYPE_STRING: // 字符串                            cellValue = cell.getStringCellValue();                            break;                        case HSSFCell.CELL_TYPE_BOOLEAN: // Boolean                            cellValue = cell.getBooleanCellValue() + "";                            break;                        case HSSFCell.CELL_TYPE_FORMULA: // 公式                            cellValue = cell.getCellFormula() + "";                            break;                        case HSSFCell.CELL_TYPE_BLANK: // 空值                            cellValue = "";                            break;                        case HSSFCell.CELL_TYPE_ERROR: // 故障                            cellValue = "非法字符";                            break;                        default:                            cellValue = "未知类型";                            break;                    }                }                System.out.print(cellValue +"\t");                rowLst.add(cellValue);            }            System.out.println();            dataLst.add(rowLst);        }        return dataLst;    }// -----------------------------------向excel写入数据    // 标题字体    private HSSFFont titleFont = null;    // private XSSFFont titleFont = null; //2007格式    // 标题样式    private HSSFCellStyle titleStyle = null;    // private XSSFCellStyle titleStyle = null;//2007格式    // 行信息内容样式    private HSSFCellStyle contentStyle = null;    // private XSSFCellStyle contentStyle = null;//2007格式    /** 写excel文件     * @throws IOException     */    public void writeExcel(String[] titleStrs,List<String[]> contentList,String filename) throws IOException{        FileOutputStream fileOut = new FileOutputStream("C:\\Users\\javaloveiphone\\Desktop\\example.xls");        /*        * severlet响应生成excel文件        * HttpServletResponse response        *        * // 文件标题        *  String head = new String(filename.getBytes("GB2312"), "ISO-8859-1");        * response.reset();        * response.setContentType("application/vnd.ms-excel");        * response.addHeader("Content-Disposition", "attachment; filename="+ head + ".xls");        *        *  HSSFWorkbook wb = new HSSFWorkbook();        *  。。。。。        *        *  java.io.OutputStream os = response.getOutputStream();        *  wb.write(os);        *  os.close();        *        */        HSSFWorkbook wb = new HSSFWorkbook();// 创建新HSSFWorkbook对象        // XSSFWorkbook wb = new XSSFWorkbook();//2007格式        setExcelStyle(wb);//执行样式初始化        HSSFSheet sheet = wb.createSheet(filename);// 创建新的sheet对象        // XSSFSheet sheet = wb.createSheet(filename);//2007格式        HSSFRow titleRow = sheet.createRow((short) 0);//创建第一行        // XSSFRow titleRow = sheet.createRow((short) 0);//2007格式        // titleRow.setHeight((short)300);//设置行高,设置太小可能被隐藏看不到        titleRow.setHeightInPoints(20);//20像素        int titleCount = titleStrs.length;// 列数        // 写标题        for (int k = 0; k < titleCount; k++) {            HSSFCell cell = titleRow.createCell((short) k); // 新建一个单元格            // XSSFCell cell = titleRow.createCell((short) k); //2007格式            // cell.setEncoding(HSSFCell.ENCODING_UTF_16); // 中文字符集转换            cell.setCellStyle(titleStyle);//设置标题样式            // cell.setCellValue(new HSSFRichTextString(titleStrs[k])); // 为单元格赋值            // cell.setCellValue(wb.getCreationHelper().createRichTextString(""));            cell.setCellType(HSSFCell.CELL_TYPE_STRING);            cell.setCellValue(titleStrs[k]);            sheet.setColumnWidth((short)k, (short)5000);//设置列宽        }        int contentCount = contentList.size();//总的记录数        // 写内容        for (int i = 0; i < contentCount; i++) {            String [] contents = contentList.get(i);            HSSFRow row = sheet.createRow((short)(i + 1)); // 新建一行            // XSSFRow row = sheet.createRow((short)(i + 1)); // //2007格式            for (int j = 0; j < titleCount; j++) {                HSSFCell cell = row.createCell((short) j); // 新建一个单元格                // XSSFCell cell = row.createCell((short) j); // //2007格式                cell.setCellStyle(contentStyle);//设置内容样式                if (contents[j] == null || contents[j].equals("null")) {                    contents[j] = "";                }                //格式化日期                if(j == 2){                    HSSFCellStyle style = wb.createCellStyle();                    // XSSFCellStyle style = wb.createCellStyle();//2007格式                    style.setDataFormat(wb.getCreationHelper().createDataFormat().getFormat("yyyy-mm-dd hh:mm:ss"));                    // cell.setCellValue(new Date());                    // cell.setCellValue(Calendar.getInstance());                    cell.setCellValue(contents[j]);                    cell.setCellStyle(style);                }else{                    cell.setCellValue(new HSSFRichTextString(contents[j]));                }            }        }        wb.write(fileOut);        fileOut.flush();        fileOut.close();    }    /** 样式初始化*/    public void setExcelStyle(HSSFWorkbook workBook){        // 设置列标题字体,样式        titleFont = workBook.createFont();        titleFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);        // 标题列样式        titleStyle = workBook.createCellStyle();        titleStyle.setBorderTop(HSSFCellStyle.BORDER_THIN); // 设置边框        titleStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);        titleStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);        titleStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);        titleStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);        titleStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);        titleStyle.setFont(titleFont);        // 内容列样式        contentStyle = workBook.createCellStyle();        contentStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);        contentStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);        contentStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);        contentStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);        contentStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);        contentStyle.setAlignment(HSSFCellStyle.ALIGN_LEFT);    }}


0 0