Excel表单的导入导出工具类(一)

对报表的处理无外乎导入导出,之前也做过不少,但都一直没有相关记录。用顺手的东西就不要抛弃,而是改装接着用。这样开发效率才能提高。

1.可以用模板方式来设定导入数据的excel模板。并获取该模板

1.1 创建模板

模板创建就是在按照页面的显示字段,整理出查询列。如下图红色部分。

这里写图片描述

1.2 读取模板

关键是获取模板在本地项目的路径。获取路径有两种区分。一种在src下,一种是在webapp下。具体可以看前面笔记中记载。
我这里说放在webapp下的情况:模板放在excelModel文件夹中。

String path=request.getSession().getServletContext().getRealPath("excelModel");
path=path.replace("\\","/");

2.模板写入的工具类

//filePath  模板文件在项目的路径
//list  要导出的数据集合
public static Workbook buildWorkBook2(String filePath,List<List<String>> list){
    FileInputStream fs=null;
    String name=new String(filePath.trim.getBytes(),Charset.forName("UTF-8"));
    File file=new File(name);
String fileName=file.getName();
if(file.exists()){
    try{
    fs=new FileInputStream(file);
}catch(FileNotFoundException e){
            logger.error("获取模板文件流时异常",e);
}
String suffex=fileName.substring(fileName.lastIndexOf("."));
Workbook web=null;
try{
web =suffex.equals(".xlsx")? new SXSSFWorkbook(new XSSFWorkbook(fs),200):new HSSFWorkbook(fs);
Sheet sheet =web.getSheetAt(0);
if(list !=null && list.size()>0){
    int dataRows =list.size();
    //填充数据
    if(int i=0;i<dataRows; i=+){
        Row row=sheeet.createRow(i+2);
        List<String> current=list.get(i);
        int cells=current.size();
        for(int j=0; j<=cells; j++){
            Cell cell=row.createCell(j,Cell.CELL_TYPE_STRING);
            if(j==0){
                cell.setCellValue(i+1);
            }
            if(current.get(j-1)==null || TKStringUtils.isEmpty(current.get(j-1)) || current.get(j-1).equals("null")){
                    cell.setCellValue("");
        }else{
            cell.setCellValue(String.valueOf(current.get(j-1)));
    }
    }
}
}

}catch(Exception e){
    throw new RuntimeException(e);
}finally{
    if(fs !=null){
        try{
        fs.close();
        }catch(IOException e){
            logger.error("数据导出时,关闭文件流异常。");
}
}
}
}
return web;
}

3.填充数据后返回页面时用到的工具类

public static void renderExcel(Workbook web,HttpServletResponse response){
    response.setContentType("application/octet-stream");
    try{
    response.addHeader("Content-Disposition","attachement;filename="+URLEncoder.encode(web.getSheetName(0)+".xlsx","utf-8"));
    OutputStream out=response.getOutputStream();
    web.write(out);
    out.flush();
    out.close();
    }catch(Exception e){
        throw new RuntimeException(e);
    }
}

4.全代码预览

这里写图片描述

猜你喜欢

转载自blog.csdn.net/zhanglf02/article/details/79851655