javaPOI导出excel工具类

生成Workbook方法

/**
 *
 * @param title 标题
 * @param str 内容
 * @return XSSFWorkbook类
 */
public static XSSFWorkbook getWorkBook(String[] title, String[][] str) {
    // 第一步,创建一个HSSFWorkbook,对应一个Excel文件
    XSSFWorkbook wb = new XSSFWorkbook();
    // 第二步,在workbook中添加一个sheet,对应Excel文件中的sheet
    XSSFSheet xssfSheet = wb.createSheet();
    // 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制
    XSSFRow firstRow = xssfSheet.createRow(0);
    // 第四步,创建单元格,并设置值表头 设置表头居中
    XSSFCellStyle style = wb.createCellStyle();
    // 创建一个居中格式
    style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
    //创建标题
    for (int i = 0; i < title.length; i++) {
        XSSFCell cell = firstRow.createCell(i);
        cell.setCellValue(title[i]);
        cell.setCellStyle(style);
    }
    //创建内容
    XSSFRow row;
    for (int i = 0; i < str.length; i++) {
        row = xssfSheet.createRow(i + 1);
        for (int j = 0; j < str[i].length; j++) {
            //将内容按顺序赋给对应的列对象
            row.createCell(j).setCellValue(str[i][j]);
        }
    }
    return wb;
}
  • 注这里XSSFWorkbook生成的是xlsx格式,如果需要xls需要用HSSFWorkbook类

使用web工程测试

public void export(HttpServletResponse response,List<Person> list) throws UnsupportedEncodingException {
    //初始化标题
    String[] titles = {"姓名","年龄","性别","身份证"};
    //封装数据
    String[][] arr = new String[list.size()][titles.length];
    for (int i = 0; i < list.size(); i++) {
        Person person = list.get(i);
        arr[i][0] = person.getName();
        arr[i][1] = person.getAge();
        arr[i][2] = person.getGender();
        arr[i][3] = person.getIDCard();
    }
    //导出excel
    XSSFWorkbook workBook = ExcelUtil.getWorkBook(titles, arr);
    //设置响应头
    String fileName = new String("ceshi.xlsx".getBytes(), "ISO8859-1");
    response.reset();
    response.setContentType("application/msexcel");
    response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
    //输出
    try (OutputStream outputStream = response.getOutputStream()) {
        workBook.write(outputStream);
        outputStream.flush();
        outputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

你可能感兴趣的:(java)