java table data export to excel case

        In the past two days, when implementing a function of exporting data to Excel, I searched for many cases on the Internet. There are many ways. One uses POI, which is implemented by inheriting the AbstractExcelView class, but with the update of the Spring version , which is gradually being deprecated. After researching many cases online, I made the following conclusions:

    1. Build the Java Web Project (Maven Build)

    2. Import the support jar:

<!-- https://mvnrepository.com/artifact/org.apache.poi/poi Excel processing support -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.15-beta2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml-schemas -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml-schemas</artifactId>
    <version>3.17</version>
</dependency>

    3. Main classes:

    Mock data entity class (Student.java):

package com.ed.util;

public class Student
{
        private String id;
        private String name;
        private String sex;
        private String birth;

        public Student()
        {
        }

        public Student(String id, String name, String sex, String birth)
        {
                this.id = id;
                this.name = name;
                this.sex = sex;
                this.birth = birth;
        }

        public String getId()
        {
                return id;
        }

        public void setId(String id)
        {
                this.id = id;
        }

        public String getName()
        {
                return name;
        }

        public void setName(String name)
        {
                this.name = name;
        }

        public String getSex()
        {
                return sex;
        }

        public void setSex(String sex)
        {
                this.sex = sex;
        }

        public String getBirth()
        {
                return birth;
        }

        public void setBirth(String birth)
        {
                this.birth = birth;
        }

}

    Control class (ExcelDemo.java):

package com.ed.util;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExcelDemo extends HttpServlet{

	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
		OutputStream os = null;
		XSSFWorkbook xWorkbook = null;
		try {
			//Define the default file name timestamp when the table is exported
			String fileName = df.format(new Date()) + ".xlsx";
			os = response.getOutputStream();
			response.reset();
			
			//Function: The front-end function is displayed as calling the browser to download the pop-up window
			response.setHeader("Content-disposition", "attachment; filename = " + URLEncoder.encode(fileName, "UTF-8"));
			/*response.setHeader("Content-disposition", "attachment; filename = " + new String(fileName.getBytes(fileName), "ISO8859-1"));*/
			response.setContentType("application/octet-streem");
			
			//create table workspace
			xWorkbook = new XSSFWorkbook();
			//create a new table
			XSSFSheet xSheet = xWorkbook.createSheet("Student Information Sheet");
			
			//set Sheet page header
			setSheetHeader (xWorkbook, xSheet);
			
			//set Sheet page content
			setSheetContent (xWorkbook, xSheet);
			
			xWorkbook.write(os);
		} catch (Exception e) {
			e.printStackTrace ();
		} finally {
			if (null != os) {
				try {
					os.close();
				} catch (Exception e) {
					e.printStackTrace ();
				}
			}
		
			if (null != xWorkbook) {
				try {
					xWorkbook.close();
				} catch (Exception e) {
					e.printStackTrace ();
				}
			}
		}
		
		response.sendRedirect("index.jsp");
	}
	
	/**
	 * Configure the top information of the Excel table, such as: student number, name, age, date of birth
	 * @param xWorkbook
	 * @param xSheet
	 */
	private void setSheetContent(XSSFWorkbook xWorkbook, XSSFSheet xSheet) {
		//Set the width of the table xSheet.setColumnWidth(0, 20 * 256); The number 20 in
		xSheet.setColumnWidth(0, 20 * 256);
		xSheet.setColumnWidth(1, 15 * 256);
		xSheet.setColumnWidth(2, 15 * 256);
		xSheet.setColumnWidth(3, 20 * 256);
		
		//create the style of the table
		CellStyle cs = xWorkbook.createCellStyle();
		//Set horizontal and vertical centering
		cs.setAlignment(CellStyle.ALIGN_CENTER);
		cs.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
		//set font
		Font headerFont = xWorkbook.createFont();
		headerFont.setFontHeightInPoints((short) 12);
		/*headerFont.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);*/
		headerFont.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
		headerFont.setFontName("California");
		cs.setFont(headerFont);
		cs.setWrapText(true);//Whether automatic line wrapping
		
		//create a row
		XSSFRow xRow0 = xSheet.createRow(0);
		//set each column
		XSSFCell xCell0 = xRow0.createCell(0);
		xCell0.setCellStyle(cs);
		xCell0.setCellValue("学号");
		
		XSSFCell xCell1 = xRow0.createCell(1);
		xCell1.setCellStyle(cs);
		xCell1.setCellValue("姓名");
		
		XSSFCell xCell2 = xRow0.createCell(2);
		xCell2.setCellStyle(cs);
		xCell2.setCellValue("Gender");    
		
		XSSFCell xCell3 = xRow0.createCell(3);
		xCell3.setCellStyle(cs);
		xCell3.setCellValue("date of birth");    
		
	}

	/**
	 * Configuration (assignment) table content part
	 * @param xWorkbook
	 * @param xSheet
	 * @throws Exception
	 */
	private void setSheetHeader(XSSFWorkbook xWorkbook, XSSFSheet xSheet) throws Exception {
		//Because of the rush, the data displayed on the front-end page are all static data. Here, a List is defined and statically written data is passed in to simulate
		List<Student> listStu = getStudent();
		
		//Create content styles (styles below the header)
		CellStyle cs = xWorkbook.createCellStyle();
		cs.setWrapText(true);
		
		//Set the horizontal and vertical centering
		cs.setAlignment(CellStyle.ALIGN_CENTER);
		cs.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
		
		if (null != listStu && listStu.size() > 0) {
			for (int i = 0; i < listStu.size(); i++) {
				XSSFRow xRow = xSheet.createRow(i + 1);
				//Set the value of the first column of student numbers
				XSSFCell xCell0 = xRow.createCell(0);
				xCell0.setCellStyle(cs);
				xCell0.setCellValue(listStu.get(i).getId());  
				//Set the value of the second column name
				XSSFCell xCell1 = xRow.createCell(1);
				xCell1.setCellStyle(cs);
				xCell1.setCellValue(listStu.get(i).getName());  
				//Set the value of the third column gender
				XSSFCell xCell2 = xRow.createCell(2);
				xCell2.setCellStyle(cs);
				xCell2.setCellValue(listStu.get(i).getSex());
				//Set the value of the fourth column gender
				XSSFCell xCell3 = xRow.createCell(3);
				xCell3.setCellStyle(cs);
				xCell3.setCellValue(listStu.get(i).getBirth());
						
			}
		}
		
	}
	
    /**
     * @Function: Provide simulation data import to Excel table
     */
    private static List<Student> getStudent() throws Exception
    {
        List<Student> list = new ArrayList<Student>();

        Student user1 = new Student("1001", "张三", "男", "1997-03-12");
        Student user2 = new Student("1002", "李四", "女", "1996-08-12");
        Student user3 = new Student("1003", "王五", "女", "1985-11-12");
        list.add(user1);
        list.add(user2);
        list.add(user3);

        return list;
    }
}

    4. jsp page

<%@page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<style>
table{
	border:1px solid #000;
}
table td{
	border:1px solid #000;
}
</style>
</head>
<body>
    <h3>Student Information Sheet</h3>
    <table>
        <thead>
            <tr>
                <td>学       号</td>
                <td>姓       名</td>
                <td>Gender</td>
                <td>Birthdate</td>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>1001</td>
                <td>Zhang San</td>
                <td>男</td>
                <td>1997-03-12</td>
            </tr>
            <tr>
                <td>1002</td>
                <td>Li Si</td>
                <td>女</td>
                <td>1996-08-12</td>
            </tr>
            <tr>
                <td>1003</td>
                <td>王五</td>
                <td>女</td>
                <td>1985-11-12</td>
            </tr>
        </tbody>
    </table>
<br>
<!-- This is important, it needs to be an Http request-->
<a style="color:red;" href="http://localhost:8080/ExcelDemo/excelStudent">导出到Excel</a>
<br>
<br>
<br>
<p style="color:red;">(Because it is too rushed, the data displayed on the front-end page are all static data, and the background defines a List to pass in statically written data to simulate)</p>
</body>
</html>

    5. web.xml configuration

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <servlet>
        <servlet-name>ExcelDemo</servlet-name>
        <servlet-class>com.ed.util.ExcelDemo</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>ExcelDemo</servlet-name>
        <url-pattern>/excelStudent</url-pattern>
    </servlet-mapping>
</web-app>

    Note: The data displayed on the front end of this case is static simulation data, and the data imported into Excel is defined in the getStudent() method of the control class ExcelDemo.java.

It is for your reference only, and I hope you can give us more pointers for the inadequacies. (Please indicate the source)




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324804924&siteId=291194637