基于POI的 excel 导出

后端代码

public void export(HttpServletResponse response) {
List userList = new ArrayList<>();
User user = new User();
user.setAddress(“安徽”);
user.setName(“张三”);
User user1 = new User();
user1.setAddress(“江苏”);
user1.setName(“李四”);
userList.add(user);
userList.add(user1);

    //创建一个工作簿
    HSSFWorkbook wb = new HSSFWorkbook();
    //创建一个工作表
    HSSFSheet sheet = wb.createSheet("客户");

    //创建一行行的索引是从0开始的,写标题
    HSSFRow row = sheet.createRow(0);
    String[] header = {"名称", "地址"};
    //创建单元格,列的索引是从0开始
    HSSFCell cell = null;
    for (int i = 0; i < header.length; i++) {
        row.createCell(i).setCellValue(header[i]);
    }

    //创建数据行
    for (int i = 1; i <= userList.size(); i++) {
        HSSFRow row1 = sheet.createRow(i);
        row1.createCell(0).setCellValue(userList.get(i-1).getName());
        row1.createCell(1).setCellValue(userList.get(i-1).getAddress());

    }

// File file = new File(“E:\lianxi\aa.xls”);
// try {
// wb.write(file);
// wb.close();
// } catch (IOException e) {
// e.printStackTrace();
// }

    OutputStream out = null;
    try {
        out = response.getOutputStream();
        String fileName = "enroll.xls";// 文件名
        response.setContentType("application/x-msdownload");
        response.setHeader("Content-Disposition", "attachment; filename="
                + URLEncoder.encode(fileName, "UTF-8"));
        wb.write(out);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

前段代码
location.href=“http://localhost:8080/terminal/exportController”;
注意事项: 不能用ajax

发布了33 篇原创文章 · 获赞 0 · 访问量 226

猜你喜欢

转载自blog.csdn.net/lemonmr/article/details/103582388