Java实现Excel导出(一)

不同于excel导入,下面例子的excel导出是在后台java代码中实现,在页面上点击导出按钮,所有的工作都在后台进行,下面是使用POI的方式导出excel。
由于时间有限,所以就没写前端页面,下面的例子是通过在浏览器中输入导出方法的地址来弹出窗口
主要实现将下面数据库表导出至excel
Java实现Excel导出(一)_第1张图片
Java文件
entity实体 StudentGrade.java

package com.env.entity;
import javax.persistence.Entity;
import javax.persistence.Table;
import com.env.common.entity.BaseBO;

@Entity
@Table(name="s_grade")
public class StudentGrade extends BaseBO {

    private static final long serialVersionUID = 1L;

    //成绩id
    private String gid;
    
    //学生姓名
    private String studentname;
    
    //课程java
    private String java;
    
    //课程Oracle
    private String oracle;
    
    //课程数据结构
    private String struct;
    
    //总分
    private String total;

    public String getGid() {
        return gid;
    }

    public void setGid(String gid) {
        this.gid = gid;
    }

    public String getStudentname() {
        return studentname;
    }

    public void setStudentname(String studentname) {
        this.studentname = studentname;
    }

    public String getJava() {
        return java;
    }

    public void setJava(String java) {
        this.java = java;
    }

    public String getOracle() {
        return oracle;
    }

    public void setOracle(String oracle) {
        this.oracle = oracle;
    }

    public String getStruct() {
        return struct;
    }

    public void setStruct(String struct) {
        this.struct = struct;
    }

    public String getTotal() {
        return total;
    }

    public void setTotal(String total) {
        this.total = total;
    }    
}

dao层 SgradeMapper.java

package com.env.dao;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.env.entity.StudentGrade;

public interface SgradeMapper {
    List getStudentGradeList(@Param("studentname")String studentname);
}

mapper文件 SgradeMapper.xml




    

Controller层 SgradeController.java

package com.env.controller;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.env.result.Result;
import com.env.service.SgradeService;
import com.env.utils.LoggerUtil;

@RestController
@RequestMapping(value="/sGradeController")
public class SgradeController {

    @Autowired
    private SgradeService sgradeService;
    
/*
* 导出学生成绩列表至excel
*/
//导出的方法是用GET请求方式访问,后面的参数{json}用来传学生姓名,可根据学生姓名查询该学生成绩,仅导出该学生的成绩到excel,若参数为空,则导出所有学生的成绩到
//工具类Result方法
/*public static Result success(Object data){
		Result result=new Result(1,"success",data);
		return result;
}
public static Result error(String msg){
		Result result=new Result(0,msg,null);
		return result;
}*/
    @RequestMapping(method = RequestMethod.GET, value="/exportSgrade2Excel/{json}")
    public Result exportSgrade2Excel(
            @PathVariable String json,HttpServletRequest request, HttpServletResponse response) {
        try {
            json = "{"+json+"}";
            String result = sgradeService.exportSgrade2Excel(json,
                    request, response);
            return Result.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("异常,导出学生成绩到Excel失败");
        }
    }
}

Service层 SgradeService.java

package com.env.service;

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

public interface SgradeService {
    /*
     * 导出学生成绩至excel
     */
    String exportSgrade2Excel(String json, HttpServletRequest request, HttpServletResponse response) throws Exception;
}

ServiceImpl SgradeServiceImpl.java

package com.env.serviceImpl;

import java.util.ArrayList;
import java.util.List;

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

import org.apache.commons.beanutils.DynaBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.env.common.entity.PoiDataBean;
import com.env.common.entity.PoiTitleBean;
import com.env.common.utils.DynaBeanPluginsUtil;
import com.env.common.utils.ExcelPoiPluginsUtil;
import com.env.common.utils.FileToolsUtil;
import com.env.common.utils.JsonPluginsUtil;
import com.env.common.utils.Util;
import com.env.dao.SgradeMapper;
import com.env.entity.StudentGrade;
import com.env.service.SgradeService;

@Service
public class SgradeServiceImpl implements SgradeService {

    @Autowired
    private SgradeMapper sgradeMapper;
    
    /*
     * 导出学生成绩数据至excel
     */
    @Override
    public String exportSgrade2Excel(String json, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        //json字符串转换为bean对象,也可用其他工具类转换,下面的工具类中不会给出
        DynaBean bean = JsonPluginsUtil.json2bean(json);
        // 参数,可为空,为空则导出所有学生的成绩,Util.toString()是转字符串的工具类方法,下面的工具类中不会给出
        String studentname = Util.toString(bean.get("studentname"));
        
        //查询学生成绩
        List list = sgradeMapper.getStudentGradeList(studentname);
        
        // Excel模板,导出的excel文件以此为模板
        String frompath = FileToolsUtil.ROOT + "resource/excel/studentGrade.xlsx";
        // 导出的文件名称
        String filename = "学生成绩表";
        //在此处定义excel列名,须与上面所说的excel模板的一一对应
        String columnname[] = {
            "ordernum","studentname","java","oracle","数据结构","总分"
        };
        //导出到excel的所有数据保存在该list中
        List list1 = new ArrayList();
        //每一个DynaBean相当于一行数据
        DynaBean bean1 = null;
        
        //从第四行开始插入数据
        int row = 3;
        for(int i=0;i<=list.size()-1;i++){
            String studentname1 = list.get(i).getStudentname();
            String java = list.get(i).getJava();
            String oracle = list.get(i).getOracle();
            String struct = list.get(i).getStruct();
            String total = list.get(i).getTotal();
            bean1 = DynaBeanPluginsUtil.invoke();
            bean1.set("ordernum", i+1);
            bean1.set("studentname", studentname1);
            bean1.set("java", java);
            bean1.set("oracle", oracle);
            bean1.set("数据结构", struct);
            bean1.set("总分", total);
            list1.add(bean1);
            row++;
        }
        //在导出的excel表中显示查询条件(导出的是哪个学生的数据)
        String studentname2 = null;
        if (!Util.isNull(studentname) && !"-1".equals(studentname)) {
            studentname2 = studentname;
        }else{
            studentname2 = "全部";
        }
        //0和3分别表示从第一列第四行开始插入数据,list1是要插入表格的数据集合,columnname为上面定义的表的列名,为String类型数组
        PoiDataBean dataBean = new PoiDataBean(0, 3, list1, columnname);
        // 导出Excel的头部信息
        List titleBean = new ArrayList();
        String title = "学生:" + studentname2;
        PoiTitleBean selectBean = new PoiTitleBean(1, Util.toString(title));
        titleBean.add(selectBean);    
        //导出Excel工具类
        //frompath为导出excel的模板文件地址
        //filename为将导出excel文件的名称
        //titleBean为导出Excel文件的头部信息
        ExcelPoiPluginsUtil.wirte(frompath, filename, dataBean, titleBean, request, response);    
        return null;
    }
}

涉及到的主要工具类
DynaBeanPluginsUtil.java

package com.env.common.utils;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.beanutils.DynaBean;
import org.apache.commons.beanutils.DynaProperty;

public class DynaBeanPluginsUtil {   
    /**
     * 创建 DynaBean
     * @return
     */
    public static DynaBean invoke(){
        return new CommonDynaBean();
    }
    /**
     * 判断是否有此属性
     * @param _dynaBean 对象
     * @param _property   属性名称
     * @return  【true 有】【 false 无】
     */
    public static boolean IsProperty(DynaBean _dynaBean,String _property){
        return getPropertyStr(_dynaBean).indexOf(_property)!=-1?true:false;
    }    
    /**
     * 获取此对象中所含有的属性
     * @param _dynaBean
     * @param _propertys
     * @return
     */
    public static String[] havePropertys(DynaBean _dynaBean,String[] _propertys){
        
        String _tempStr = getPropertyStr(_dynaBean);
        List _list = new ArrayList();
        for(String _property : _propertys){
            if(_tempStr.indexOf(_property)!=-1){
                _list.add(_property);
            }
        }
        return _list.toArray(new String[]{});
    }    
    /**
     * 复制生成新的bean
     *
     * @param _bean         复制的对象
     * @param copyPropertys 复制某些属性
     * @param copy2Propertys复制为对应属性
     * @return
     */
    public static DynaBean copyBean(DynaBean _bean,String[] copyPropertys,String[] copy2Propertys){
        DynaBean _tempBean = invoke();
        String _tempStr = getPropertyStr(_bean);
        if(copy2Propertys!=null&©Propertys.length!=copy2Propertys.length){
            System.out.println("复制属性与复制到的属性不匹配!");
        }else{
            String _property = null;
            if(copy2Propertys==null){
                for(int _i=0;_i

PoiDataBean.java

package com.env.common.entity;
import java.util.List;

import org.apache.commons.beanutils.DynaBean;

public class PoiDataBean {
   
    public PoiDataBean(int columnstart, int rowstart, List data,
            String[] columnname) {
        super();
        this.columnstart = columnstart;
        this.rowstart = rowstart;
        this.data = data;
        this.columnname = columnname;
    }
    private int columnstart;//开始列0
    private int rowstart;//开始行0
    private List data;//数据集合
    private String[] columnname;//数据项
    private boolean tieleWirte;//是否已经写入
    
    public int getColumnstart() {
        return columnstart;
    }
    public void setColumnstart(int columnstart) {
        this.columnstart = columnstart;
    }
    public int getRowstart() {
        return rowstart;
    }
    public void setRowstart(int rowstart) {
        this.rowstart = rowstart;
    }
    public List getData() {
        return data;
    }
    public void setData(List data) {
        this.data = data;
    }
    public String[] getColumnname() {
        return columnname;
    }
    public void setColumnname(String[] columnname) {
        this.columnname = columnname;
    }
    public boolean isTieleWirte() {
        return tieleWirte;
    }
    public void setTieleWirte(boolean tieleWirte) {
        this.tieleWirte = tieleWirte;
    }
}

PoiTitleBean.java

package com.env.common.entity;
/**
* 导出excel的头部信息
*/
public class PoiTitleBean {

    private int row;//行数
    private String title;//标题
    private int call = 0;//列数
    public int getRow() {
        return row;
    }
    public PoiTitleBean(int row, String title) {
        super();
        this.row = row;
        this.title = title;
    }
    public void setRow(int row) {
        this.row = row;
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public int getCall() {
        return call;
    }
    public void setCall(int call) {
        this.call = call;
    }
}

ExcelPoiPluginsUtil.java

package com.env.common.utils;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.DynaBean;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.ClientAnchor;
import org.apache.poi.ss.usermodel.Drawing;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.factory.annotation.Value;

import com.env.common.entity.ExcelPicBean;
import com.env.common.entity.PoiDataBean;
import com.env.common.entity.PoiTitleBean;

/**
* Excel 解析、读写工具类
*
* 需要
* poi-3.9-20121203.jar
* poi-ooxml-3.9-20121203.jar
* poi-ooxml-schemas-3.9-20121203.jar
* xmlbeans-2.3.0.jar
* 支持
* @author
*
*/
public class ExcelPoiPluginsUtil {

    private static final int EXCELMAXCOUNT = 5000;
    private static final String EXCEL_ROOT = "resource\\excel\\";
    private static final String EXCEL_SUB = "excel";
    
    public static final int HSSFCell_CELL_TYPE_STRING = HSSFCell.CELL_TYPE_STRING;

    public static List inikPoiTitleBean(int _start, String[] _titles){
        List _poiTitleBeanList = new ArrayList();
        PoiTitleBean _poiTitleBean = null;
        for(int _i=0;_i<_titles.length;_i++){
            _poiTitleBean = new PoiTitleBean(_start+_i, _titles[_i]);
            _poiTitleBeanList.add(_poiTitleBean);
        }
        return _poiTitleBeanList;
    }
    /**
     *
     * @param data            数据
     * @param frompath        模板路径
     * @param filename        文件名称
     * @param columnstart    开始列0
     * @param rowstart        开始行0
     * @return
     * @throws IOException
     * @throws RowsExceededException
     * @throws WriteException
     */
    public static DynaBean wirte(List> data,String frompath ,String filename , int columnstart, int rowstart) throws IOException
    {
        DynaBean _dynaBean = DynaBeanPluginsUtil.invoke();
        int fileCount = getFileCount(data.size());
        
        String downFile = null;
        if(fileCount==1){
            downFile =  EXCEL_ROOT + UUIDToolsUtil.getUUID(EXCEL_SUB) + frompath.substring(frompath.lastIndexOf("."),frompath.length());
            String toPath = FileToolsUtil.ROOT + downFile;
            wirte( data, frompath, toPath, columnstart,  rowstart, 0,  data.size());
        }else{
            String felie = UUIDToolsUtil.getUUID(EXCEL_SUB);
            String sourceDir = EXCEL_ROOT  + felie;
            for(int _h=1;_h<=fileCount;_h++){
                String filePath =  sourceDir +"\\" + filename + "_" + _h +frompath.substring(frompath.lastIndexOf("."),frompath.length());
                String toPath = FileToolsUtil.ROOT + filePath;
                wirte( data, frompath, toPath, columnstart,  rowstart, (_h-1)*EXCELMAXCOUNT,  _h==fileCount?(data.size()-(_h-1)*EXCELMAXCOUNT):EXCELMAXCOUNT);
            }
            
            downFile = sourceDir + ".zip";
            String zipFile = FileToolsUtil.ROOT + downFile;
            ZipPluginsUtil.zip(FileToolsUtil.ROOT + sourceDir + "\\", zipFile);
        }
        
        _dynaBean.set("fileCount", fileCount);
        _dynaBean.set("downFile", downFile);
        _dynaBean.set("filename", filename);
        
        return _dynaBean;
    }
    
    public static DynaBean  wirte(List> data,String frompath , int columnstart, int rowstart) throws IOException
    {
        return wirte(data, frompath , UUIDToolsUtil.getUUID(EXCEL_SUB) ,  columnstart,  rowstart);
    }
    
    private static void  wirte(List> data,String frompath,String topath, int columnstart, int rowStart, int dataStart, int dataCount) throws IOException
    {
        
        FileToolsUtil.copyFile(frompath, topath);
        
//        初始化
        Workbook wb = null;
        InputStream inp = new FileInputStream(topath);
        
//
        int rowCount = 0;
        rowCount = rowStart + dataCount;
        
        int i = dataStart;
        try {
            
            wb = WorkbookFactory.create(inp);
            
            Sheet sheet = wb.getSheetAt(0);
            
             for(int _i = rowStart; _i  _i_data=data.get(i);
                   if(_row==null){
                       _row= sheet.createRow(_i);
                   }
                   _row.setHeight((short) 500);
                   int columnCount = _i_data.size()+columnstart;//需要加上开始的列数
                   int j = 0;//需要额外的计数
                   for(int _j = columnstart; _j  _poiTitleBean,
            HttpServletRequest request, HttpServletResponse response) throws IOException {
        String toPath = FileToolsUtil.TMPPATH + UUIDToolsUtil.getUUID(EXCEL_SUB) +
                frompath.substring(frompath.lastIndexOf("."),frompath.length());
        wirte(frompath, toPath, filename, 0, _poiDataBean.getData().size(), _poiDataBean, _poiTitleBean, request, response);
    }
    
    private static void  wirte(String frompath, String topath, String filename, int dataStart, int dataCount, PoiDataBean _poiDataBean, List _poiTitleBean,
            HttpServletRequest request, HttpServletResponse response) throws IOException {
        
        // response输出流
        ServletOutputStream out = response.getOutputStream();
        // 文件名外加当前时间
        DateFormat format = new SimpleDateFormat("yyyyMMdd");
        String timeFileName = format.format(new Date());
        timeFileName =encodingFileName(filename + "_" + timeFileName);
        // 设置response必要参数
        response.reset();
        response.setContentType("application/octet-stream; charset=iso-8859-1");
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename=" + timeFileName +".xlsx" );    
        
       List data = _poiDataBean.getData();
       int columnstart = _poiDataBean.getColumnstart();
       int rowStart = _poiDataBean.getRowstart();
       String[] columnname = _poiDataBean.getColumnname();
        
        if(FileToolsUtil.copyFile(frompath, topath)){
            // 初始化
            Workbook wb = null;
            InputStream inp = new FileInputStream(topath);
            
            int rowCount = 0;
            rowCount = rowStart + dataCount;
            
            int i = dataStart;
            
            try {
                
                wb = WorkbookFactory.create(inp);
                
                Sheet sheet = wb.getSheetAt(0);
                
                 Row _row = sheet.getRow(_poiDataBean.getRowstart());
                 int columnCount = columnname.length+columnstart;//需要加上开始的列数
                 Cell _cell = null;
                 Map _callTypeMap0 = new HashMap();
                 Cell cell = _row.getCell(_poiDataBean.getColumnstart());

                  for(int _j = columnstart; _j  _callTypeMap1 = new HashMap();
                  cell = _row.getCell(_poiDataBean.getColumnstart());

                  for(int _j = columnstart; _j 0){
                        
                        for(PoiTitleBean _title : _poiTitleBean){
                            _row = sheet.getRow(_title.getRow());
                            cell = _row.getCell(_title.getCall());
                            cell.setCellValue(_title.getTitle());
                        }
                    }
                }
                
                
                 for(int _i = rowStart; _i  _callTypeMap = null;
                       if(_i%2!=0){
                           _callTypeMap = _callTypeMap0;
                       }else{
                           _callTypeMap = _callTypeMap1;
                       }
                       int j = 0;//需要额外的计数
                       for(int _j = columnstart; _j 

Excel模板文件 studentGrade.xlsx
Java实现Excel导出(一)_第2张图片
实现效果
studentname参数为空的情况
浏览器地址栏
地址1
回车
Java实现Excel导出(一)_第3张图片
导出的数据
Java实现Excel导出(一)_第4张图片
studentname参数不为空的情况
浏览器地址栏
地址2
导出的数据
Java实现Excel导出(一)_第5张图片
至此,导出规则的excel就搞定了

你可能感兴趣的:(Java)