Jxls export Excel

Export Excel using Jxls in Springboot

Add the dependent

  <! --Jxls Excel-->
        <dependency>
            <groupId>org.jxls</groupId>
            <artifactId>jxls</artifactId>
            <version>2.8.1</version>
 </dependency>   <! --To use Apache POI API based transformer implementation add the following dependency -->  <dependency>  <groupId>org.jxls</groupId>  <artifactId>jxls-poi</artifactId>  <version>2.8.1</version>  </dependency>   <! --To use Java Excel API based transformer implementation add the following dependency -->  <! -- https://mvnrepository.com/artifact/org.jxls/jxls-jexcel -->  <dependency>  <groupId>org.jxls</groupId>  <artifactId>jxls-jexcel</artifactId>  <version>1.0.9</version>  </dependency> Copy the code

Define the exported entity classFish.java

package com.gaolei.app.entity;

import lombok.Data;

/ * * * @author DuebassLei  * @version 1.0  * @date 2020/10/12 17:07 * / @Data public class Fish {  / * ** the name* * /  private String name;   / * ** price* * /  private String price;   / * ** varieties* * /  private String kind;  } Copy the code

defineexcelThe template


Defining the controllerJxlsController.java

@Slf4j
@Controller
@RequestMapping(value = "/api/jxls")
public class JxlsController {
    @PostMapping(value = "export")
 public void jxlsExport(HttpServletRequest request,HttpServletResponse response) throws IOException {  log.info("Jxls export Excel data");   // Simulate data  List<Fish> fishList = new ArrayList<>();  for (int i = 0; i < 100 ; i++) {  Fish fish = new Fish();  fish.setName("Little carp"+i);  fish.setKind("Carp"+i);  fish.setPrice("20"+i);  fishList.add(fish);  }   InputStream is = new ClassPathResource("templates/fish.xls").getInputStream();  OutputStream os = null;  try {  os = response.getOutputStream();  response.addHeader("Content-Disposition"."attachment; filename=" + "fish.xls");  response.setContentType("application/octet-stream");  Context context = new Context();  context.putVar("fishList", fishList);  JxlsHelper.getInstance().processTemplate(is, os, context);  } catch (IOException e) {  e.printStackTrace();  }finally {  os.flush();  os.close();  }  }  } Copy the code

Postman test

The test interface address: http://localhost:9999/api/jxls/export


## Export data effect


For more details seeJxlsThe officialApi

Source: Gitee /Duebasslei

This article is formatted using MDNICE