java表格数据导出到Excel案例

        这两天在实现一个将数据导出到Excel功能的时候,在网上搜索了很多案例,方式有多种,有一种使用POI的,用到继承AbstractExcelView这个类来进行实现,但是随着Spring版本的更新,这个逐渐被弃用。在网上查阅诸多案例之后,做了如下总结:

    1. 构建Java Web项目(Maven构建)

    2. 导入支持jar:



    org.apache.poi
    poi-ooxml
    3.15-beta2



    org.apache.poi
    poi-ooxml-schemas
    3.17

    3.主要类:

    模拟数据实体类(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;
        }

}

    控制类(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 {
			//定义表格导出时默认文件名 时间戳
			String fileName = df.format(new Date()) + ".xlsx";
			os = response.getOutputStream();
			response.reset();
			
			//作用:在前端作用显示为调用浏览器下载弹窗
			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");
			
			//创建表格工作空间
			xWorkbook = new XSSFWorkbook();
			//创建一个新表格
			XSSFSheet xSheet = xWorkbook.createSheet("学生信息表");
			
			//set Sheet页头部
			setSheetHeader(xWorkbook, xSheet);
			
			//set Sheet页内容
			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");
	}
	
	/**
	 * 配置Excel表格的顶部信息,如:学号  姓名  年龄  出生年月
	 * @param xWorkbook
	 * @param xSheet
	 */
	private void setSheetContent(XSSFWorkbook xWorkbook, XSSFSheet xSheet) {
		//设置表格的宽度  xSheet.setColumnWidth(0, 20 * 256); 中的数字 20 自行设置为自己适用的
		xSheet.setColumnWidth(0, 20 * 256);
		xSheet.setColumnWidth(1, 15 * 256);
		xSheet.setColumnWidth(2, 15 * 256);
		xSheet.setColumnWidth(3, 20 * 256);
		
		//创建表格的样式
		CellStyle cs = xWorkbook.createCellStyle();
		//设置水平、垂直居中
		cs.setAlignment(CellStyle.ALIGN_CENTER);
		cs.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
		//设置字体
		Font headerFont = xWorkbook.createFont();
		headerFont.setFontHeightInPoints((short) 12);
		/*headerFont.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);*/
		headerFont.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
		headerFont.setFontName("宋体");
		cs.setFont(headerFont);
		cs.setWrapText(true);//是否自动换行
		
		//创建一行
		XSSFRow xRow0 = xSheet.createRow(0);
		//设置每一列
		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("性别");    
		
		XSSFCell xCell3 = xRow0.createCell(3);
		xCell3.setCellStyle(cs);
		xCell3.setCellValue("出生年月");    
		
	}

	/**
	 * 配置(赋值)表格内容部分
	 * @param xWorkbook
	 * @param xSheet
	 * @throws Exception 
	 */
	private void setSheetHeader(XSSFWorkbook xWorkbook, XSSFSheet xSheet) throws Exception {
		//由于太过匆忙,前端页面显示的数据都是静态数据,此处定义了一个List传入了静态写死的数据来模拟
		List listStu = getStudent();
		
		//创建内容样式(头部以下的样式)
		CellStyle cs = xWorkbook.createCellStyle();
		cs.setWrapText(true);
		
		//设置水平垂直居中
		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);
				//设置第一列学号的值
				XSSFCell xCell0 = xRow.createCell(0);
				xCell0.setCellStyle(cs);
				xCell0.setCellValue(listStu.get(i).getId());  
				//设置第二列姓名的值
				XSSFCell xCell1 = xRow.createCell(1);
				xCell1.setCellStyle(cs);
				xCell1.setCellValue(listStu.get(i).getName());  
				//设置第三列性别的值
				XSSFCell xCell2 = xRow.createCell(2);
				xCell2.setCellStyle(cs);
				xCell2.setCellValue(listStu.get(i).getSex()); 
				//设置第四列性别的值
				XSSFCell xCell3 = xRow.createCell(3);
				xCell3.setCellStyle(cs);
				xCell3.setCellValue(listStu.get(i).getBirth()); 
						
			}
		}
		
	}
	
    /**
     * @功能:提供模拟数据导入到Excel表格
     */
    private static List getStudent() throws Exception
    {
        List list = new ArrayList();

        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 contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>






    

学生信息表

                                                                                                                                                                                                                                                                                                                                                                                                                                     
学 号姓 名性 别出生年月
1001张三1997-03-12
1002李四1996-08-12
1003王五1985-11-12

导出到Excel


(由于太过匆忙,前端页面显示的数据都是静态数据,后台定义了一个List传入了静态写死的数据来模拟)

    5. web.xml配置




  
        ExcelDemo
        com.ed.util.ExcelDemo
    

    
        ExcelDemo
        /excelStudent
    

    注:此案例在前端展示的数据为静态模拟数据,导入Excel中的数据由控制类ExcelDemo.java的getStudent()方法中定义。

仅供大家参考,不足之处望大家多多指点。(转载请注明出处)




你可能感兴趣的:(Java)