poi的基础使用方法

推荐POI的用户使用手册:http://poi.apache.org/spreadsheet/quick-guide.html#NewWorkbook

 HSSFCellStyle (POI API Documentation)   poi使用方法
 /**
     * 将对应的数据写入excel文件
     * @param head 文件的名称(同时也是文件的头)
     * @param colName 文件各列的解释说明,与content的内容对应
     * @param content 需要被输入到文件的内容
     * @return String 返回创建的文件的名称
     */
    public String inputContentToExcel(String head,String[] colName,List<List> content) throws IOException {
        String path = getExportDir();
        File file = new File(path);
        if(!file.exists()){
            file.mkdirs();
        }
        path += "/" + head + ".xls";
        File currentFile = new File(path);
        if(!currentFile.exists()){
            file.mkdir();
        }
        int colCount = colName.length;
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet(head);
        //创建第一行为标题行
        HSSFRow row1 = sheet.createRow(0);
        HSSFCell cell1 = row1.createCell((short)0);
        cell1.setCellValue(head);
        //创建第二行为每列的标题
        HSSFRow row2 = sheet.createRow(1);
        for(short col=0;col<colCount;col++){
            HSSFCell cell = row2.createCell(col);
            String val = colName[col];
            cell.setCellValue(Validator.isNULL(val) ? "" : val);
        }
        //创建输入内容的各行
        int rowInd = 2;
        for (List list : content){
            HSSFRow row = sheet.createRow(rowInd);
            for(short j=0;j<colCount;j++){
                HSSFCell cell = row.createCell(j);
                String val = list.get(j).toString();
                cell.setCellValue(val);
            }
            rowInd++;
        }

        //合并标题行
        sheet.addMergedRegion(new Region(0,(short)0,0,(short)(colCount-1)));
        //标题的样式
        HSSFFont font = wb.createFont();
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);    //加粗
        font.setFontHeightInPoints((short)18);            //设置字号大小
        font.setFontName("宋体");                         //设置字体
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);     //居中方式
        style.setFont(font);
        cell1.setCellStyle(style);
        //根据内容自动调整宽度
        for(short k=0;k<colCount;k++){
            sheet.autoSizeColumn(k);
        }

        //开始写入数据
        FileOutputStream stream = new FileOutputStream(path);
        wb.write(stream);
        stream.close();
        return head + ".xls";
    }

获取路径的方法

public String getExportDir(){
        String dir = "";
        dir = configService.getFileRealPath() + "export/";
        //获取当前的年月日,创建文件目录
        Calendar calendar = Calendar.getInstance();
        dir += calendar.get(Calendar.YEAR) + "/" + (calendar.get(Calendar.MONTH)+1) + "/" + calendar.get(Calendar.DATE) ;
        System.out.println("当前的文件路径为:"+dir);
        return dir;
    }

效果图如附件

猜你喜欢

转载自814318774.iteye.com/blog/1870470