JAVA method of exporting an EXCEL table: first use HSSFWorkbook to open or create an "Excel file object"; then use the Sheet object to return the row object, and use the row object to get the Cell object; then read and write the Cell object; and finally generate file into the responsive front-end page.
How to export EXCEL table from JAVA:
Basic steps:
First, we What you should know is that an Excel file corresponds to a workbook, a workbook is composed of multiple sheets, and a sheet is composed of multiple rows and cells.
Then the correct sequence when we use poi to export an Excel table should be:
1. Use HSSFWorkbook to open or create an "Excel file object"
2. Use the HSSFWorkbook object to return or create the Sheet object
3. Use the Sheet object to return the row object, and use the row object to get the Cell object
4. Read and write the Cell object.
5. Put the generated HSSFWorkbook into HttpServletResponse and respond to the front-end page
Export Excel application instance:
Tool class code:
package com.yq.util; 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 { /** * 導(dǎo)出Excel * @param sheetName sheet名稱 * @param title 標(biāo)題 * @param values 內(nèi)容 * @param wb HSSFWorkbook對(duì)象 * @return */ public static HSSFWorkbook getHSSFWorkbook(String sheetName,String []title,String [][]values, HSSFWorkbook wb){ // 第一步,創(chuàng)建一個(gè)HSSFWorkbook,對(duì)應(yīng)一個(gè)Excel文件 if(wb == null){ wb = new HSSFWorkbook(); } // 第二步,在workbook中添加一個(gè)sheet,對(duì)應(yīng)Excel文件中的sheet HSSFSheet sheet = wb.createSheet(sheetName); // 第三步,在sheet中添加表頭第0行,注意老版本poi對(duì)Excel的行數(shù)列數(shù)有限制 HSSFRow row = sheet.createRow(0); // 第四步,創(chuàng)建單元格,并設(shè)置值表頭 設(shè)置表頭居中 HSSFCellStyle style = wb.createCellStyle(); style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 創(chuàng)建一個(gè)居中格式 //聲明列對(duì)象 HSSFCell cell = null; //創(chuàng)建標(biāo)題 for(int i=0;i<title.length;i++){ cell = row.createCell(i); cell.setCellValue(title[i]); cell.setCellStyle(style); } //創(chuàng)建內(nèi)容 for(int i=0;i<values.length;i++){ row = sheet.createRow(i + 1); for(int j=0;j<values[i].length;j++){ //將內(nèi)容按順序賦給對(duì)應(yīng)的列對(duì)象 row.createCell(j).setCellValue(values[i][j]); } } return wb; } }
Controller code:
@Controller @RequestMapping(value = "/report") public class ReportFormController extends BaseController { @Resource(name = "reportService") private ReportManager reportService; /** * 導(dǎo)出報(bào)表 * @return */ @RequestMapping(value = "/export") @ResponseBody public void export(HttpServletRequest request,HttpServletResponse response) throws Exception { //獲取數(shù)據(jù) List<PageData> list = reportService.bookList(page); //excel標(biāo)題 String[] title = {"名稱","性別","年齡","學(xué)校","班級(jí)"}; //excel文件名 String fileName = "學(xué)生信息表"+System.currentTimeMillis()+".xls"; //sheet名 String sheetName = "學(xué)生信息表"; for (int i = 0; i < list.size(); i++) { content[i] = new String[title.length]; PageData obj = list.get(i); content[i][0] = obj.get("stuName").tostring(); content[i][1] = obj.get("stuSex").tostring(); content[i][2] = obj.get("stuAge").tostring(); content[i][3] = obj.get("stuSchoolName").tostring(); content[i][4] = obj.get("stuClassName").tostring(); } //創(chuàng)建HSSFWorkbook HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null); //響應(yīng)到客戶端 try { this.setResponseHeader(response, fileName); OutputStream os = response.getOutputStream(); wb.write(os); os.flush(); os.close(); } catch (Exception e) { e.printStackTrace(); } } //發(fā)送響應(yīng)流方法 public void setResponseHeader(HttpServletResponse response, String fileName) { try { try { fileName = new String(fileName.getBytes(),"ISO8859-1"); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } response.setContentType("application/octet-stream;charset=ISO8859-1"); response.setHeader("Content-Disposition", "attachment;filename="+ fileName); response.addHeader("Pargam", "no-cache"); response.addHeader("Cache-Control", "no-cache"); } catch (Exception ex) { ex.printStackTrace(); } } }
Front-end page code:
<button id="js-export" type="button" class="btn btn-primary">導(dǎo)出Excel</button> $('#js-export').click(function(){ window.location.href="/report/exportBooksTable.do; });
Related learning recommendations: java basics
The above is the detailed content of How to export EXCEL table from JAVA. 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.

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

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;

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.

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.

TheJVMenablesJava’s"writeonce,runanywhere"capabilitybyexecutingbytecodethroughfourmaincomponents:1.TheClassLoaderSubsystemloads,links,andinitializes.classfilesusingbootstrap,extension,andapplicationclassloaders,ensuringsecureandlazyclassloa

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
