java xls导出小样例

xiaoxiao2021-02-27  331

做项目的时候时不时会碰到需求要xls导出,这个实现起来很简单.但是平时用的也很少,所以一般人见了都会头疼起码我是这样.今天我整理出一个小样例.

直接删干货

1.maven支持包

<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.9</version> </dependency> 2.准备数据(一般都是查询出一个list数据集合)

List<Map> guessList = guessService.statistics(startTime, endTime, pageIndex, pageSize); 3.创建xls对象

a.创建一个book

HSSFWorkbook workbook = new HSSFWorkbook(); b.创建一个sheet HSSFSheet sheet = workbook.createSheet("导出信息"); c.创建第一行表头 HSSFRow row0 = sheet.createRow(0);HSSFCell cell0 = row0.createCell(0);//创建单元格 cell0.setCellValue(new HSSFRichTextString("日期")); HSSFCell cell1 = row0.createCell(1); cell1.setCellValue(new HSSFRichTextString("下注次数")); HSSFCell cell2 = row0.createCell(2); cell2.setCellValue(new HSSFRichTextString("下注人数")); HSSFCell cell3 = row0.createCell(3); cell3.setCellValue(new HSSFRichTextString("下注狮牙数"));d.加载数据for(int i=0;i<guessList.size();i++){ Map map = guessList.get(i); HSSFRow row = sheet.createRow(i + 1); HSSFCell cellI0 = row.createCell(0); cellI0.setCellValue(new HSSFRichTextString(map.get("data_time").toString())); HSSFCell cellI1 = row.createCell(1); cellI1.setCellValue(new HSSFRichTextString(map.get("total_cnt").toString())); HSSFCell cellI2 = row.createCell(2); cellI2.setCellValue(new HSSFRichTextString(map.get("user_cnt").toString())); HSSFCell cellI3 = row.createCell(3); cellI3.setCellValue(new HSSFRichTextString(map.get("change_cnt").toString())); }e.导出数据try{ ServletOutputStream outSTr = null; String excelFileName = "竞猜统计导出文件" + DateUtils.timeToStr(new Date()) + ".xls";//文件名称 resp.setContentType("application/msexcel;charset=UTF-8"); resp.addHeader("Content-Disposition", "attachment;filename=\"" + new String(excelFileName.getBytes("GBK"), "ISO8859_1") + "\""); outSTr = resp.getOutputStream(); workbook.write(outSTr); outSTr.flush(); outSTr.close();}catch (Exception e){ e.printStackTrace();}至此一个简单的xls文件导出就算完工了

转载请注明原文地址: https://www.6miu.com/read-3491.html

最新回复(0)