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);
    }

  • 相关阅读:
    loadrunner下检查点乱码情况处理
    Linux下安装loadrunner步骤及遇到的问题
    当你决定不再在乎的时候,生活就好起来了
    受难语录
    LoadRunner--内存指标介绍
    Microsoft Visual Studio Web 创作组件安装失败的解决方法
    (六)微服务分布式云架构spring cloud
    (五)微服务分布式云架构
    (四)微服务分布式云架构
    (三)微服务分布式云架构
  • 原文地址:https://www.cnblogs.com/yzf666/p/7110901.html
Copyright © 2011-2022 走看看