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

Implementation of automatic completion of Docker commands

Preface I don't know how long this friend has...

MySQL database terminal - common operation command codes

Table of contents 1. Add users 2. Change the user...

How to use Element in React project

This is my first time using the element framework...

Mysql GTID Mha configuration method

Gtid + Mha + Binlog server configuration: 1: Test...

Introduction to keyword design methods in web design

Many times, we ignore the setting of the web page ...

How to set the memory size of Docker tomcat

When installing Tomcat in Docker, Tomcat may over...

Uniapp's experience in developing small programs

1. Create a new UI project First of all, our UI i...

4 ways to view processes in LINUX (summary)

A process is a program code that runs in the CPU ...

How to install MySQL and Redis in Docker

This article is based on the CentOS 7.3 system en...

How to deploy Vue project under nginx

Today I will use the server nginx, and I also nee...

The whole process of installing gogs with pagoda panel and docker

Table of contents 1 Install Docker in Baota Softw...

Linux CentOS MySQL database installation and configuration tutorial

Notes on installing MySQL database, share with ev...

The Complete Guide to Grid Layout in CSS

Grid is a two-dimensional grid layout system. Wit...