导入-导出Excle文件

@Action("areaAction_exportExcel")
public String exportExcel() throws IOException {
    List<Area> list = areaService.findAll();
    // 在内存中创建了一个Excel文件
    HSSFWorkbook workbook = new HSSFWorkbook();
    // 创建一个sheet
    HSSFSheet sheet = workbook.createSheet("区域数据");
    // 创建标题行
    HSSFRow titleRow = sheet.createRow(0);
    // 创建列
    titleRow.createCell(0).setCellValue("省");
    titleRow.createCell(1).setCellValue("市");
    titleRow.createCell(2).setCellValue("区");
    titleRow.createCell(3).setCellValue("邮编");
    titleRow.createCell(4).setCellValue("简码");
    titleRow.createCell(5).setCellValue("城市编码");
    for (Area area : list) {
        HSSFRow dataRow = sheet.createRow(sheet.getLastRowNum() + 1);
        // 创建列
        dataRow.createCell(0).setCellValue(area.getProvince());
        dataRow.createCell(1).setCellValue(area.getCity());
        dataRow.createCell(2).setCellValue(area.getDistrict());
        dataRow.createCell(3).setCellValue(area.getPostcode());
        dataRow.createCell(4).setCellValue(area.getShortcode());
        dataRow.createCell(5).setCellValue(area.getCitycode());
    }
    String fileName = "区域数据.xls";
    HttpServletRequest request = ServletActionContext.getRequest();
    String agent = request.getHeader("User-Agent");
    // 对文件名重新进行编码
    fileName = FileUtils.encodeDownloadFilename(fileName, agent);
    // 一个流两个头
    HttpServletResponse response = ServletActionContext.getResponse();
    // 设置文件的类型
    response.setContentType(
            ServletActionContext.getServletContext().getMimeType(fileName));
    // 设置Content-Disposition头信息
    response.setHeader("Content-Disposition",
            "attachment; filename=" + fileName);
    // 输出流
    ServletOutputStream os = response.getOutputStream();
    // 写出文件
    workbook.write(os);
    // 释放资源
    workbook.close();
    return NONE;
    }

猜你喜欢

转载自blog.csdn.net/tomcatandoracle/article/details/80278556