Java uses Apache.POI to export HSSFWorkbook to Excel

Java uses Apache.POI to export HSSFWorkbook to Excel

Use HSSFWorkbook in Apache.POI to export to Excel. The specific content is as follows:

1. Introduce Poi dependency (3.12)

The dependencies are as follows:

<dependency>
   <groupId>org.apache.poi</groupId>
   <artifactId>poi</artifactId>
   <version>3.12</version>
</dependency>

2. Create entity class (User.java)

package com.kd.nm.entity.pojo;

/**
 * Entity class (User)
 *
 * author Xiaochen Gege*/
public class User {
 // User number private String userNo;
 //User nameprivate String userName;
 //Ageprivate String age;

 // No parameter construction public User() {
 }

 // Constructor with parameters public User(String userNo, String userName, String age) {
  this.userNo = userNo;
  this.userName = userName;
  this.age = age;
 }

 // Encapsulate get and set methods public String getUserNo() {
  return userNo;
 }

 public void setUserNo(String userNo) {
  this.userNo = userNo;
 }

 public String getUserName() {
  return userName;
 }

 public void setUserName(String userName) {
  this.userName = userName;
 }

 public String getAge() {
  return age;
 }

 public void setAge(String age) {
  this.age = age;
 }

 //Rewrite toString method @Override
 public String toString() {
  return "User{" +
    "userNo='" + userNo + '\'' +
    ", userName='" + userName + '\'' +
    ", age='" + age + '\'' +
    '}';
 }
}

3.Excel related tool classes (ExcelUtil, ReflectUtil)

package com.kd.nm.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.poi.hssf.usermodel.*;

/**
 * Description: Excel related tools*
 * @author: Brother Xiaochen*
 */
public class ExcelUtil {

 /**
  * Generate excel table* @param heads header content* @param data data content* @return
  */
 public static HSSFWorkbook createExcel(Map<String, String> heads, List data) {

  //Declare a workbook HSSFWorkbook workbook = new HSSFWorkbook();
  // Generate a table HSSFSheet sheet = workbook.createSheet();

  // Generate title row style HSSFCellStyle headStyle = creatStyle(workbook, (short) 14);

  // Generate table content style HSSFCellStyle bodyStyle = creatStyle(workbook, (short) 10);

  // Title elements List<String> keys = new ArrayList<String>(heads.keySet());

  // Pixel unit short px = 1000;
  // Set column width for (int columnIndex = 0; columnIndex < keys.size(); columnIndex++) {

   sheet.setColumnWidth(columnIndex, 6 * px);
  }

  // Generate table for (int rowNum = 0; rowNum <= data.size(); rowNum++) {

   // Create row HSSFRow row = sheet.createRow(rowNum);

   for (int cellNum = 0; cellNum < keys.size(); cellNum++) {

    // Create column HSSFCell cell = row.createCell(cellNum);

    // Title if (rowNum == 0) {

     cell.setCellStyle(headStyle);
     cell.setCellValue(heads.get(keys.get(cellNum)));
    } else { // Content cell.setCellStyle(bodyStyle);
     // Get cell through reflection.setCellValue(ReflectUtil.getValue(keys.get(cellNum), data.get(rowNum - 1)));
    }
   }
  }

  return workbook;
 }

 /**
  * Generate style * @param workbook
  * @param size
  * @return
  */
 public static HSSFCellStyle creatStyle(HSSFWorkbook workbook, short size) {

  HSSFCellStyle style = workbook.createCellStyle();
  style.setAlignment((HSSFCellStyle.ALIGN_CENTER));
  style.setVerticalAlignment((HSSFCellStyle.VERTICAL_CENTER));
  HSSFFont font = workbook.createFont();
  font.setFontHeightInPoints(size);
  font.setFontName("Microsoft YaHei");
  style.setFont(font);
  style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
  style.setBorderTop(HSSFCellStyle.BORDER_THIN);
  style.setBorderRight(HSSFCellStyle.BORDER_THIN);
  style.setBorderLeft(HSSFCellStyle.BORDER_THIN);

  return style;
 }
}
package com.kd.nm.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ReflectionUtils;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;

/**
 * Reflection Toolkit*
 * @author: Brother Xiaochen*/
public class ReflectUtil {

 private static final Logger logger = LoggerFactory.getLogger(ReflectUtil.class);

 public static String getValue(String key, Object obj) {

  String value = "";

  try {

   // Get the current property PropertyDescriptor pd = new PropertyDescriptor(key, obj.getClass());
   // Get the get method Method getMd = pd.getReadMethod();
   value = getMd.invoke(obj).toString();
  } catch (Exception e) {

   logger.error("Failed to get content!");
   e.printStackTrace();
  }

  return value;
 }

 public static void setValue(String key, String value, Object obj) {

  try {

   // Get the current property PropertyDescriptor pd = new PropertyDescriptor(key, obj.getClass());
   // Get the set method Method writeMd = pd.getWriteMethod();
   writeMd.invoke(obj, value);
  } catch (Exception e) {

   logger.error("Failed to set content!");
   e.printStackTrace();
  }
 }
}

4. Backend controller code

@RequestMapping(value = "/exportExcel",method = RequestMethod.GET,produces = "application/json")
 public void exportExcel(HttpServletResponse httpServletResponse) throws IOException {

  // Header content (can be set on the front end and passed in via parameters) Key is the attribute value of the entity class, value is the label of the header
  Map<String,String> head = new HashMap<>();
  head.put("userNo","User No.");
  head.put("userName","user name");
  head.put("age","age");

  //Table data content, simulating the data queried from the database List<User> data = new ArrayList<>();
  data.add(new User("1","Little Chen's brother","18"));
  data.add(new User("2","Little Piggy Sister","18"));
  data.add(new User("3","Big Pig Brother","18"));
  
  
  // Generate workbook HSSFWorkbook hssfWorkbook = ExcelUtil.createExcel(head, data);

  // Define the file name String fileName = "Export Excel table";

  httpServletResponse.setHeader("Cache-Control", "max-age=0");
  httpServletResponse.setContentType("application/vnd.ms-excel");
  httpServletResponse.addHeader("Content-disposition", "attachment;filename=" + new String(fileName.getBytes("gb2312"),
    "ISO-8859-1") + ".xls");

  OutputStream outputStream = httpServletResponse.getOutputStream();

  hssfWorkbook.write(outputStream);
  outputStream.flush();
  outputStream.close();
 }

5. Access the mapped address

Interface access:

http://localhost:9090/FaultTreatment/api/standard/exportExcel

insert image description here
insert image description here

This is the end of this article about how to implement exporting HSSFWorkbook to Excel in Java using Apache.POI. For more information about exporting HSSFWorkbook to Excel in Apache.POI, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Java application EasyExcel tool class
  • Sample code for using Alibaba open source technology EasyExcel to operate Excel tables in Java
  • Java uses easyExcel to export excel data case
  • Teach you how to import Excel data into MySQL using Java
  • Java to add watermarks in Excel (single watermark, tiled watermark)
  • How to quickly and elegantly export Excel in Java
  • Easypoi in Java implements excel multi-sheet import and export function
  • Java reads simple excel general tool class
  • Java steps to use poi to import Excel data into the database
  • Java uses EasyExcel to import and export Excel

<<:  Detailed explanation of the application of the four states of hyperconnection

>>:  JS array deduplication details

Recommend

Pure CSS code to achieve drag effect

Table of contents 1. Drag effect example 2. CSS I...

Basic tutorial on using explain statement in MySQL

Table of contents 1. Overview 1. Explain statemen...

How to Rename a Group of Files at Once on Linux

In Linux, we usually use the mv command to rename...

The marquee tag in HTML achieves seamless scrolling marquee effect

The <marquee> tag is a tag that appears in ...

JavaScript recursion detailed

Table of contents 1. What is recursion? 2. Solve ...

Vue3.0 uses the vue-grid-layout plug-in to implement drag layout

Table of contents 1. Plugins 2. Interlude 3. Impl...

How to use echarts to visualize components in Vue

echarts component official website address: https...

Three methods of automatically completing commands in MySQL database

Note: The third method is only used in XSell and ...

Summary of MySQL database and table sharding

During project development, our database data is ...

Summary of MySQL logical backup and recovery testing

Table of contents 1. What kind of backup is a dat...

Vue3.0 project construction and usage process

Table of contents 1. Project construction 2: Dire...