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>
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(); } }
Create a new interface Service
import java.util.List; public interface UserService { public List<User> findAllUser(); }
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; } }
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){ // 第一步,創(chuàng)建一個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的行數(shù)列數(shù)有限制 HSSFRow row = sheet.createRow(0); HSSFRow row1 = sheet1.createRow(0); HSSFRow row2 = sheet2.createRow(0); // 第四步,創(chuàng)建單元格樣式,并設置值表頭 設置表頭居中 HSSFCellStyle style = wb.createCellStyle(); style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 創(chuàng)建一個居中格式 //聲明單元格 HSSFCell cell = null; //創(chuàng)建標題 for(int i=0;i<title.length;i++){ //創(chuàng)建一個單元格 cell = row.createCell(i); //給單元格賦值 cell.setCellValue(title[i]); //給單元格設置樣式 cell.setCellStyle(style); } //創(chuàng)建標題 for(int i=0;i<title.length;i++){ //創(chuàng)建一個單元格 cell = row1.createCell(i); //給單元格賦值 cell.setCellValue(title[i]); //給單元格設置樣式 cell.setCellStyle(style); } //創(chuàng)建內(nèi)容 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++){ //將內(nèi)容按順序賦給對應的列對象 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++){ //將內(nèi)容按順序賦給對應的列對象 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++){ //將內(nèi)容按順序賦給對應的列對象 row2.createCell(j).setCellValue(app[j]); } } } return wb; } }
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 請求的參數(shù) user = new User(); user.setUsername(username); } UserService userService = new UserServiceImpl(); //獲取數(shù)據(jù) List<User> list = userService.findAllUser(); //excel標題 String[] title = {"姓名", "郵箱", "創(chuàng)建時間", "最近登錄時間","角色","是否可用"}; //excel文件名 String fileName = System.currentTimeMillis() + ".xls"; //sheet名 String sheetName = "用戶信息"; String sheetName1 = "hello"; String sheetName2 = "xixi"; //沒有數(shù)據(jù)就傳入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(); } } //創(chuàng)建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(); } } }
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:
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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

itertools.combinations is used to generate all non-repetitive combinations (order irrelevant) that selects a specified number of elements from the iterable object. Its usage includes: 1. Select 2 element combinations from the list, such as ('A','B'), ('A','C'), etc., to avoid repeated order; 2. Take 3 character combinations of strings, such as "abc" and "abd", which are suitable for subsequence generation; 3. Find the combinations where the sum of two numbers is equal to the target value, such as 1 5=6, simplify the double loop logic; the difference between combinations and arrangement lies in whether the order is important, combinations regard AB and BA as the same, while permutations are regarded as different;

DependencyInjection(DI)isadesignpatternwhereobjectsreceivedependenciesexternally,promotingloosecouplingandeasiertestingthroughconstructor,setter,orfieldinjection.2.SpringFrameworkusesannotationslike@Component,@Service,and@AutowiredwithJava-basedconfi

fixture is a function used to provide preset environment or data for tests. 1. Use the @pytest.fixture decorator to define fixture; 2. Inject fixture in parameter form in the test function; 3. Execute setup before yield, and then teardown; 4. Control scope through scope parameters, such as function, module, etc.; 5. Place the shared fixture in conftest.py to achieve cross-file sharing, thereby improving the maintainability and reusability of tests.

java.lang.OutOfMemoryError: Javaheapspace indicates insufficient heap memory, and needs to check the processing of large objects, memory leaks and heap settings, and locate and optimize the code through the heap dump analysis tool; 2. Metaspace errors are common in dynamic class generation or hot deployment due to excessive class metadata, and MaxMetaspaceSize should be restricted and class loading should be optimized; 3. Unabletocreatenewnativethread due to exhausting system thread resources, it is necessary to check the number of threads, use thread pools, and adjust the stack size; 4. GCoverheadlimitexceeded means that GC is frequent but has less recycling, and GC logs should be analyzed and optimized.

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear

The core of mastering Advanced SpringDataJPA is to select the appropriate data access method based on the scenario and ensure performance and maintainability. 1. In custom query, @Query supports JPQL and native SQL, which is suitable for complex association and aggregation operations. It is recommended to use DTO or interface projection to perform type-safe mapping to avoid maintenance problems caused by using Object[]. 2. The paging operation needs to be implemented in combination with Pageable, but beware of N 1 query problems. You can preload the associated data through JOINFETCH or use projection to reduce entity loading, thereby improving performance. 3. For multi-condition dynamic queries, JpaSpecifica should be used
