导出Excel结合springboot(直接在浏览器下载)

1.前端:一个超链接就可以了

<a href="/news/export">导出Excel</a>

2.服务端:

1).controller:

import javax.servlet.http.HttpServletResponse;
@GetMapping("/export")
public Object export(HttpServletResponse response){  
   String sheetName = "订单统计表单";
   String titleName = "订单数据统计表";
   String fileName = "订单统计表单.xls";
   int columnNumber = 3;
   int[] columnWidth = { 40, 20, 30 };
   String[][] dataList = { { "ORD-98-20180803170744-1650", "2016-03-08", "纯牛奶" },
        { "ORD-98-20180803171214-1987", "2017-06-04", "核桃" }, { "ORD-98-20180803172217-1110", "2017-12-06", "画   报" } };
  String[] columnName = { "订单号", "创建时间", "商品名称" };

  try {
    ByteArrayInputStream byteArrayInputStream = ExcelUtil.ExportWithResponse(sheetName,             
           titleName, fileName,columnNumber, columnWidth, columnName, dataList,response);
    renderBinary(byteArrayInputStream,fileName);

  } catch (Exception e) {
    e.printStackTrace();
  }
}

2).工具类

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.CellRangeAddress;
import org.apache.poi.hssf.util.HSSFColor;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
public static ByteArrayInputStream ExportWithResponse(String sheetName, String titleName,
                        String fileName, int columnNumber, int[] columnWidth,
                        String[] columnName, String[][] dataList,
                             HttpServletResponse response) throws Exception {
   ByteArrayInputStream inputStream = null;
   if (columnNumber == columnWidth.length && columnWidth.length == columnName.length) {
      // 第一步,创建一个webbook,对应一个Excel文件
      HSSFWorkbook wb = new HSSFWorkbook();

// 为数据内容设置特点新单元格样式1 自动换行 上下居中
HSSFCellStyle zidonghuanhang = wb.createCellStyle();
zidonghuanhang.setWrapText(true);// 设置自动换行
zidonghuanhang.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 创建一个居中格式

// 设置边框
zidonghuanhang.setBottomBorderColor(HSSFColor.BLACK.index);
zidonghuanhang.setBorderBottom(HSSFCellStyle.BORDER_THIN);
zidonghuanhang.setBorderLeft(HSSFCellStyle.BORDER_THIN);
zidonghuanhang.setBorderRight(HSSFCellStyle.BORDER_THIN);
zidonghuanhang.setBorderTop(HSSFCellStyle.BORDER_THIN);
      // 第二步,在webbook中添加一个sheet,对应Excel文件中的sheet
      HSSFSheet sheet = wb.createSheet(sheetName);
      // sheet.setDefaultColumnWidth(15); //统一设置列宽
      for (int i = 0; i < columnNumber; i++)
      {
         for (int j = 0; j <= i; j++)
         {
            if (i == j)
            {
               sheet.setColumnWidth(i, columnWidth[j] * 256); // 单独设置每列的宽
            }
         }
      }
      // 创建第0行 也就是标题
      HSSFRow row1 = sheet.createRow((int) 0);
      row1.setHeightInPoints(50);// 设备标题的高度
      // 第三步创建标题的单元格样式style2以及字体样式headerFont1
      HSSFCellStyle style2 = wb.createCellStyle();
      style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
      style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
      style2.setFillForegroundColor(HSSFColor.LIGHT_TURQUOISE.index);
      style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
      HSSFFont headerFont1 = (HSSFFont) wb.createFont(); // 创建字体样式
      headerFont1.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 字体加粗
      headerFont1.setFontName("黑体"); // 设置字体类型
      headerFont1.setFontHeightInPoints((short) 15); // 设置字体大小
      style2.setFont(headerFont1); // 为标题样式设置字体样式

      HSSFCell cell1 = row1.createCell(0);// 创建标题第一列
      sheet.addMergedRegion(new CellRangeAddress(0, 0, 0,
            columnNumber - 1)); // 合并列标题
      cell1.setCellValue(titleName); // 设置值标题
      cell1.setCellStyle(style2); // 设置标题样式

      // 创建第1行 也就是表头
      HSSFRow row = sheet.createRow((int) 1);
      row.setHeightInPoints(37);// 设置表头高度

      // 第四步,创建表头单元格样式 以及表头的字体样式
      HSSFCellStyle style = wb.createCellStyle();
      style.setWrapText(true);// 设置自动换行
      style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
      style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 创建一个居中格式

      style.setBottomBorderColor(HSSFColor.BLACK.index);
      style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
      style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
      style.setBorderRight(HSSFCellStyle.BORDER_THIN);
      style.setBorderTop(HSSFCellStyle.BORDER_THIN);

      HSSFFont headerFont = (HSSFFont) wb.createFont(); // 创建字体样式
      headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 字体加粗
      headerFont.setFontName("黑体"); // 设置字体类型
      headerFont.setFontHeightInPoints((short) 10); // 设置字体大小
      style.setFont(headerFont); // 为标题样式设置字体样式

      // 第四.一步,创建表头的列
      for (int i = 0; i < columnNumber; i++)
      {
         HSSFCell cell = row.createCell(i);
         cell.setCellValue(columnName[i]);
         cell.setCellStyle(style);
      }

      // 第五步,创建单元格,并设置值
      for (int i = 0; i < dataList.length; i++)
      {
         row = sheet.createRow((int) i + 2);
         

         // 为数据内容设置特点新单元格样式2 自动换行 上下居中左右也居中
         HSSFCellStyle zidonghuanhang2 = wb.createCellStyle();
         zidonghuanhang2.setWrapText(true);// 设置自动换行
         zidonghuanhang2
               .setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 创建一个上下居中格式
         zidonghuanhang2.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中

         // 设置边框
         zidonghuanhang2.setBottomBorderColor(HSSFColor.BLACK.index);
         zidonghuanhang2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
         zidonghuanhang2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
         zidonghuanhang2.setBorderRight(HSSFCellStyle.BORDER_THIN);
         zidonghuanhang2.setBorderTop(HSSFCellStyle.BORDER_THIN);
         HSSFCell datacell = null;
         for (int j = 0; j < columnNumber; j++)
         {
            datacell = row.createCell(j);
            datacell.setCellValue(dataList[i][j]);
            datacell.setCellStyle(zidonghuanhang2);
         }
      }

      // 第六步,将文件存到浏览器设置的下载位置

      response.setContentType("application/ms-excel;charset=UTF-8");
      response.setHeader("Content-Disposition", "attachment;filename="
            .concat(String.valueOf(URLEncoder.encode(fileName, "UTF-8"))));
      OutputStream out = response.getOutputStream();
      //OutputStream out = new FileOutputStream(filename);
      //ByteArrayOutputStream out = new ByteArrayOutputStream();
      try {
         wb.write(out);// 将数据写出去
         //inputStream = new ByteArrayInputStream(out.toByteArray());
         String str = "导出" + fileName + "成功!";
         System.out.println(str);
      } catch (Exception e) {
         e.printStackTrace();
         String str1 = "导出" + fileName + "失败!";
         System.out.println(str1);
      } finally {
         out.flush();
         out.close();
      }

   } else {
      System.out.println("列数目长度名称三个数组长度要一致");
   }
   return inputStream;
}

工具类是参考一些资料的,按照上面的步骤基本上是可以完成导出Excel功能的;

具体的原理还是有待去研究,要想搞透这个还是要仔细去看一下这些代码.

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
Spring Boot是一个快速开发框架,Spring Boot的特点是可以快速开发,容易组合,简洁,生产就绪等等。而导出Excel文件也是常用的需求,为了方便大家,Spring Boot提供了一些简单的方式来导出Excel文件。 首先,需要引入以下依赖: ``` <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.0.0</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.0.0</version> </dependency> ``` 接着,需要定义一个数据类,并在该类中定义对应的属性,如下: ``` @Data public class ExcelData { private String name; private Integer age; private String address; } ``` 在Controller中定义一个返回Excel文件的接口,如下: ``` @RequestMapping("/downloadExcel") public void downloadExcel(HttpServletResponse response) throws IOException { // 创建Excel workbook对象 XSSFWorkbook workbook = new XSSFWorkbook(); // 创建Excel sheet对象 XSSFSheet sheet = workbook.createSheet("学生信息"); // 定义表头 XSSFRow header = sheet.createRow(0); header.createCell(0).setCellValue("姓名"); header.createCell(1).setCellValue("年龄"); header.createCell(2).setCellValue("地址"); // 添加数据 List<ExcelData> dataList = new ArrayList<>(); dataList.add(new ExcelData("张三", 20, "北京")); dataList.add(new ExcelData("李四", 25, "上海")); dataList.add(new ExcelData("王五", 30, "广州")); for (int i = 0; i < dataList.size(); i++) { XSSFRow row = sheet.createRow(i + 1); row.createCell(0).setCellValue(dataList.get(i).getName()); row.createCell(1).setCellValue(dataList.get(i).getAge()); row.createCell(2).setCellValue(dataList.get(i).getAddress()); } // 设置下载文件名以及响应头 response.setHeader("Content-Disposition", "attachment;filename=student.xlsx"); response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); // 输出Excel文件 workbook.write(response.getOutputStream()); } ``` 最后,在浏览器中访问该接口,即可下载Excel文件student.xlsx。 上面是基于Spring Boot导出Excel表格的简单流程,我们完全可以根据需求对其中的样式和结构进行定制和完善,例如通过自定义Excel样式和数据源来获得更好的导出效果。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值