Spring项目如何做Excel文件导出功能

/**Controller层*/
/**excel标题 */
String[] title = new String[12];
title[0] = "用户名称";
title[1] = "手机号";
title[2] = "所属工会";
title[3] = "所属话题";
title[4] = "动态标题";
title[5] = "动态内容";
title[6] = "点赞数";
title[7] = "评论数";
title[8] = "分享数";
title[9] = "阅读数";
title[10] = "发布时间";
title[11] = "是否为热门";

/**sheet名 */
String sheetName = "动态列表记录";
String[][] content = new String[list.size()][12];
Map<String, Object> map = new HashMap<String, Object>();
/**循环取出从数据库中查出的记录list,一行一行填充Excel表*/
for (int i = 0; i < list.size(); i++) {
	map = list.get(i);
	content[i][0] = map.get("userName") == null ? "-" : map.get("userName").toString();
	content[i][1] = map.get("userMobile") == null ? "-" : map.get("userMobile").toString();
	content[i][2] = map.get("unionName") == null ? "-" : map.get("unionName").toString();
	content[i][3] = map.get("topicTitle") == null ? "-" : map.get("topicTitle").toString();
	content[i][4] = map.get("dynamicTitle") == null ? "-" : map.get("dynamicTitle").toString();
	content[i][5] = map.get("dynamicContent") == null ? "-" : map.get("dynamicContent").toString();
	content[i][6] = map.get("dymamicLikeNum") == null ? "-" : map.get("dymamicLikeNum").toString();
	content[i][7] = map.get("dymamicRviewNum") == null ? "-" : map.get("dymamicRviewNum").toString();
	content[i][8] = map.get("dymamicShareNum") == null ? "-" : map.get("dymamicShareNum").toString();
	content[i][9] = map.get("dymamicReadNum") == null ? "-" : map.get("dymamicReadNum").toString();
	content[i][10] = map.get("createTime") == null ? "-" : map.get("createTime").toString();

	String flagHot = "-";
	if("0".equals(map.get("flagHot").toString())){
		flagHot = "否";
	}else if("1".equals(map.get("flagHot").toString())){
		flagHot = "是";
	}
	content[i][11] = flagHot;
}
	HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);
	/** 响应到客户端 */
	try {
		ExcelUtil.setResponseHeader(response, sheetName);
		OutputStream os = response.getOutputStream();
		wb.write(os);
		os.flush();
		os.close();
	} catch (Exception e) {
		log.error(e.getMessage());
		e.printStackTrace();
	}
		return ResultBean.ok("导出成功");

ExcelUtil工具类:

public static HSSFWorkbook getHSSFWorkbook(String sheetName, String[] title, String[][] values, HSSFWorkbook wb) {
        if (wb == null) {
            wb = new HSSFWorkbook();
        }
        HSSFSheet sheet = wb.createSheet(sheetName);
        HSSFRow row = sheet.createRow(0);
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment((short)2);
        HSSFFont font2 = wb.createFont();
        font2.setBoldweight((short)700);
        font2.setFontHeightInPoints((short)12);
        style.setFont(font2);
        HSSFCell cell = null;

        int i;
        for(i = 0; i < title.length; ++i) {
            cell = row.createCell(i);
            cell.setCellValue(title[i]);
            cell.setCellStyle(style);
        }
        for(i = 0; i < values.length; ++i) {
            row = sheet.createRow(i + 1);

            for(int j = 0; j < values[i].length; ++j) {
                row.createCell(j).setCellValue(values[i][j]);
            }
        }
        for(i = 0; i < title.length; ++i) {
            sheet.setColumnWidth(i, title[i].getBytes().length * 2 * 256);
        }
        return wb;
    }
public static void setResponseHeader(HttpServletResponse response, String fileName) {
     try {
          response.setContentType("application/vnd.ms-excel;charset=UTF-8");
          response.setHeader("Pragma", "public");
          response.setHeader("Cache-Control", "must-revalidate");
          response.setDateHeader("Expires", 0L);
          response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes("utf-8"), "ISO-8859-1") + ".xls");
      } catch (Exception var3) {
          var3.printStackTrace();
      }
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在Spring Boot中导出Excel文件,可以使用Apache POI库。以下是一个简单的示例: 1. 添加POI依赖到pom.xml文件: ```xml <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.1.0</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.0</version> </dependency> ``` 2. 创建一个Controller方法来生成Excel文件: ```java @GetMapping("/export") public void exportToExcel(HttpServletResponse response) throws IOException { // 创建工作簿 Workbook workbook = new XSSFWorkbook(); // 创建工作表 Sheet sheet = workbook.createSheet("Sheet 1"); // 创建表头行 Row headerRow = sheet.createRow(0); headerRow.createCell(0).setCellValue("Name"); headerRow.createCell(1).setCellValue("Age"); // 填充数据 List<Person> people = personService.getAllPeople(); int rowNum = 1; for (Person person : people) { Row row = sheet.createRow(rowNum++); row.createCell(0).setCellValue(person.getName()); row.createCell(1).setCellValue(person.getAge()); } // 设置响应头 response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); response.setHeader("Content-Disposition", "attachment; filename=\"people.xlsx\""); // 输出Excel文件 OutputStream outputStream = response.getOutputStream(); workbook.write(outputStream); outputStream.close(); } ``` 3. 在上面的代码中,我们首先创建了一个工作簿和一个工作表。然后创建表头行和填充数据行。最后,将响应设置为Excel文件,并将工作簿写入响应输出流中。 4. 在上面的代码中,我们使用了一个名为Person的类来存储人员信息。您需要根据您的数据模型调整代码。 这就是在Spring Boot中导出Excel文件的基本步骤。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值