java对excel的简单导出

@BeforeDownload
InputStream download(String fileName, DataModel model, DataProgress dataProgress) {
    //获取模板路径和临时存放的路径
    String templatePath = PathHelper.getClassRoot() + "/template/mar/deckMaintenanceHeader_template.xls";
    String outPutTemplatePath = PathHelper.getClassRoot() + "/template/mar/deckMaintenanceHeader_output" + strTime + ".xls";
    //定义工作簿
    HSSFWorkbook workbook = null;
    try {
        FileInputStream  inputStream=new FileInputStream(new File(templatePath));
        workbook=new HSSFWorkbook(inputStream);
        inputStream.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    HSSFSheet sheet=workbook.getSheetAt(0);

    //这里可以获取需要的数据
    
    //这里是一个添加一行的样板 
    HSSFRow r=sheet.getRow(i+3)    //获取原始的一行
    sheet.shiftRows(i+4,sheet.getLastRowNum(),1)   //把原始那行的下一行整体向下移一行
    HSSFRow rowCell=sheet.createRow(i+4)     //把原始那行的下一行创建一行新的
    for (int k=0;k<r.getLastCellNum();k++){   //对原始行每列进行遍历
        HSSFCell newCell=rowCell.createCell(k)   //获取新的单元格
        HSSFCell oldCell=r.getCell(k)           //获取原始单元格
        //对单元格复制样式
        newCell.setCellStyle(oldCell.getCellStyle())
        newCell.setCellType(oldCell.getCellType())
        newCell.setCellComment(oldCell.getCellComment())
        newCell.getCellStyle().setBorderBottom( oldCell.getCellStyle().getBorderBottom())//这个样式我暂时不知道是什么

    }


    //这个是通过四个位置来合并单元格
    CellRangeAddress cra2=new CellRangeAddress(25,1,9,10)
    sheet.addMergedRegion(cra)
    //写入数据样式
    sheet.getRow(0).getCell(0).setCellValue("对第一列第一行写入值");

    //写入临时文件
    workbook.write(new FileOutputStream(outPutTemplatePath));
    //输出
    return  new FileInputStream(new File(outPutTemplatePath));
}

猜你喜欢

转载自blog.csdn.net/mihl520/article/details/84583987
今日推荐