zoukankan      html  css  js  c++  java
  • 导出数据库数据到Excel表

    后台需要将用户信息数据导入到Excel表中提供给相关人员:

    首先查询数据就不多说了;

    导入Excel表直接亮代码(采用的是jxl的jar包提供的方法):

    public static File ImportToExcel(List<String> data,String title) {
    log.info("数据导入条数:{},标题:{}",data.size(),title);
    WritableWorkbook workbook = null;
    WritableSheet sheet = null;
    Label label = null;
    if (!title.equals("cellphone") && !title.equals("email")) {
    log.info("数据标题不正确");
    return null;
    }
    // 创建Excel表
    File file = null;
    try {
    file = new File(System.getProperty("java.io.tmpdir")+title+".xlsx");
    workbook = Workbook.createWorkbook(file);
    //workbook = Workbook.createWorkbook(os);

    // 创建Excel表中的sheet
    sheet = workbook.createSheet("First Sheet", 0);

    // 向Excel中添加数据
    int row = 0;
    // 添加标题
    label = new Label(0, row, title.equals("cellphone") ? "手机信息表" : "邮箱信息表");
    // log.debug("标题:"+i+"---"+row +"---"+ colName);
    sheet.addCell(label);
    log.debug("写入标题成功");
    for (int i = 0; i < data.size(); i++) {
    label = new Label(0, i+1, data.get(i));
    sheet.addCell(label);
    }
    log.debug("写入内容成功");

    // 关闭文件
    workbook.write();
    workbook.close();
    log.info("数据成功写入Excel");
    } catch (RowsExceededException e) {
    log.debug(e.getMessage());
    } catch (WriteException e) {
    log.debug(e.getMessage());
    } catch (IOException e) {
    log.debug(e.getMessage());
    } finally {
    try {
    workbook.close();
    } catch (Exception e) {
    }
    }
    return file;
    }

    思路:先创建一个tomcat临时文件的Excel表:new File(System.getProperty("java.io.tmpdir")+title+".xlsx")

    再用jxl提供的接口方法将数据写入表中;最后将表下载到本地:

    File file = ExcelUtil.ImportToExcel(data, name);
    response.addHeader("Content-Type", "application/vnd.ms-excel");
    response.addHeader("Content-Disposition","attachment; filename="+file.getName());
    InputStream is = null;
    OutputStream os = null;
    try {
    is = new FileInputStream(file);
    os = response.getOutputStream();
    IOUtils.copy(is, os);
    response.flushBuffer();
    } catch (Exception e) {
    e.printStackTrace();
    } finally {
    IOUtils.closeQuietly(is);
    IOUtils.closeQuietly(os);
    }

  • 相关阅读:
    sqlserver json 查询
    分页算法
    context.Response.AddHeader("Access-Control-Allow-Origin", context.Request.Headers["Origin"]); 这个方法是有问题的,AJAX跨域解决方案 在IE11中 context.Request.Headers["Origin"] 这段是获取不到值的。
    NativeWindow 妙用,截取windows消息
    屏蔽浏览器 F12
    linux常用基础命令40条
    shell之正则
    Go语言学习思路与开发软件VScode安装
    shell基础
    docker harbor安装失败
  • 原文地址:https://www.cnblogs.com/yzf666/p/7110901.html
Copyright © 2011-2022 走看看