Home Java Javagetting Started Java implements exporting excel files

Java implements exporting excel files

Oct 27, 2020 pm 05:14 PM
excel file java

Java implements exporting excel files

The implementation method is as follows:

(Video tutorial recommendation: java course)

1. First create a new SpringBoot project

2. Import dependencies –pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.2.6.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.briup</groupId>
	<artifactId>demo3</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<name>demo3</name>
	<description>Demo project for Spring Boot</description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-tomcat</artifactId>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.6</version>
            <exclusions>
                <exclusion>
                    <groupId>javax.servlet</groupId>
                    <artifactId>servlet-api</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>log4j</groupId>
                    <artifactId>log4j</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>
Copy after login

3. Create various classes

New entity class

Remember to add get/set methods

public class User {
	
	private String username;
	private String email;
	private String createTime;
	private String LastLoginTime;
	private String roleName;
	private String enable;
	public User() {
		super();
	}
}
Copy after login

Create a new interface Service

import java.util.List;

public interface UserService {
	public List<User> findAllUser();
}
Copy after login

Create a new Impl that implements the Service interface

import java.util.List;

public class UserServiceImpl implements UserService {
	@Override
	public List<User> findAllUser() {
		User user = new User();
		return null;
	}

}
Copy after login

Create a new ExcelUtil tool class

import java.util.List;
import java.util.Map;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class ExcelUtil {
    public static HSSFWorkbook getHSSFWorkbook(String sheetName,String sheetName1,String sheetName2, String []title, String[]  content,String[] app){
    	 
        // 第一步,创建一个HSSFWorkbook,对应一个Excel文件
        HSSFWorkbook wb = new HSSFWorkbook();
 
        // 第二步,在workbook中添加一个sheet,对应Excel文件中的sheet
        HSSFSheet sheet = wb.createSheet(sheetName);
        HSSFSheet sheet1 = wb.createSheet(sheetName1);
        HSSFSheet sheet2 = wb.createSheet(sheetName2);
 
        // 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制
        HSSFRow row = sheet.createRow(0);
        HSSFRow row1 = sheet1.createRow(0);
        HSSFRow row2 = sheet2.createRow(0);
 
        // 第四步,创建单元格样式,并设置值表头 设置表头居中
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
 
        //声明单元格
        HSSFCell cell = null;
 
        //创建标题
        for(int i=0;i<title.length;i++){
            //创建一个单元格
            cell = row.createCell(i);
            //给单元格赋值
            cell.setCellValue(title[i]);
            //给单元格设置样式
            cell.setCellStyle(style);
        }
        //创建标题
        for(int i=0;i<title.length;i++){
            //创建一个单元格
            cell = row1.createCell(i);
            //给单元格赋值
            cell.setCellValue(title[i]);
            //给单元格设置样式
            cell.setCellStyle(style);
        }
 
        //创建内容
        if (content != null && content.length > 0){
        	for(int i=0;i<content.length;i++){
        		row = sheet.createRow(i + 1);
        		for(int j=0;j<content.length;j++){
                    //将内容按顺序赋给对应的列对象
                    row.createCell(j).setCellValue(content[j]);
                }

            }
        }

        if (content != null && content.length > 0){
        	for(int i=0;i<content.length;i++){
        		row1 = sheet1.createRow(i + 1);
        		for(int j=0;j<content.length;j++){
                    //将内容按顺序赋给对应的列对象
                    row1.createCell(j).setCellValue(content[j]);
                }

            }
        }
        if (app != null && app.length > 0){
        	for(int i=0;i<app.length;i++){
        		row2 = sheet2.createRow(i + 1);
        		for(int j=0;j<app.length;j++){
                    //将内容按顺序赋给对应的列对象
                    row2.createCell(j).setCellValue(app[j]);
                }
            }
        }
        return wb;
    }
}
Copy after login

Create a new Controller class

import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/MyTest")
public class HelloController {
    @ResponseBody
    @RequestMapping("/hello")
    public void export(@RequestBody(required = false) User user,String username,HttpServletResponse response) throws Exception {
    	
        if (user ==null && !StringUtils.isEmpty(username)){
            //GET 请求的参数
            user = new User();
            user.setUsername(username);
        }
        UserService userService = new UserServiceImpl();
		//获取数据
        List<User> list = userService.findAllUser();
       
        //excel标题
        String[] title = {"姓名", "邮箱", "创建时间", "最近登录时间","角色","是否可用"};
 
        //excel文件名
        String fileName = System.currentTimeMillis() + ".xls";
 
        //sheet名
        String sheetName = "用户信息";
        String sheetName1 = "hello";
        String sheetName2 = "xixi";
 
        //没有数据就传入null吧,Excel工具类有对null判断
        String[] content= {"ali","aaa","ddd","aaa","aaa","aaaa"};
        String[] app= {"bbbb","bbbb","bbbb","bbbb","bbbb","bbbb",};
        if (list != null && list.size() > 0){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            for (int i = 0; i < list.size(); i++) {
                User obj = list.get(i);
                
                content[1] = obj.getUsername();
                content[1] = obj.getEmail();
                content[2] = obj.getCreateTime() == null ? "" : sdf.format(obj.getCreateTime());
                content[3] = obj.getLastLoginTime() == null ? "": sdf.format(obj.getLastLoginTime());
                content[4] = obj.getRoleName();
            }
        }
        if (list != null && list.size() > 0){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            for (int i = 0; i < list.size(); i++) {
                User obj = list.get(i);
                
                app[1] = obj.getUsername();
                app[1] = obj.getEmail();
                app[2] = obj.getCreateTime() == null ? "" : sdf.format(obj.getCreateTime());
                app[3] = obj.getLastLoginTime() == null ? "": sdf.format(obj.getLastLoginTime());
                app[4] = obj.getRoleName();
            }
        }
 
        //创建HSSFWorkbook
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName,sheetName1,sheetName2, title, content,app);
//        HSSFWorkbook wb1 = ExcelUtil.getHSSFWorkbook(sheetName1, title, content);
 
        //响应到客户端
        try {
            fileName = new String(fileName.getBytes(), "UTF-8");
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Copy after login

Set application .properties
server.port=8081
The most important thing to note is: the Application class must be in the outermost package! ! !

4. The last visit to

localhost:8081/MyTest/hello

resulted:

Java implements exporting excel files

did not write the front end, You can write an html, set an a tag, and click the event.

Related recommendations:Getting started with java

The above is the detailed content of Java implements exporting excel files. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

See all articles