1. 程式人生 > >Java實現Excel匯出(一)

Java實現Excel匯出(一)

不同於excel匯入,下面例子的excel匯出是在後臺java程式碼中實現,在頁面上點選匯出按鈕,所有的工作都在後臺進行,下面是使用POI的方式匯出excel。 由於時間有限,所以就沒寫前端頁面,下面的例子是通過在瀏覽器中輸入匯出方法的地址來彈出視窗 主要實現將下面資料庫表匯出至excel 資料庫表 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<StudentGrade> getStudentGradeList(@Param("studentname")String studentname);
}

mapper檔案 SgradeMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.env.dao.SgradeMapper">
    <select id="getStudentGradeList"   resultType="com.env.entity.StudentGrade">
        select
        gid,studentname,struct,java,oracle,total
        from s_grade
        <if test="studentname!=null and studentname!=''">
        where studentname = #{studentname}
        </if>
    </select>
</mapper>

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<StudentGrade> 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<DynaBean> list1 = new ArrayList<DynaBean>();
        //每一個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<PoiTitleBean> titleBean = new ArrayList<PoiTitleBean>();
        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<String> _list = new ArrayList<String>();
        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&&copyPropertys.length!=copy2Propertys.length){
            System.out.println("複製屬性與複製到的屬性不匹配!");
        }else{
            String _property = null;
            if(copy2Propertys==null){
                for(int _i=0;_i<copyPropertys.length;_i++){
                    _property = copyPropertys[_i];
                    if(_tempStr.indexOf(_property)!=-1){
                        _tempBean.set(_property, _bean.get(_property));
                    }else{
                        _tempBean.set(_property, null);
                    }
                }
            }else{
                for(int _i=0;_i<copyPropertys.length;_i++){
                    _property = copyPropertys[_i];
                    if(_tempStr.indexOf(_property)!=-1){
                        _tempBean.set(copy2Propertys[_i], _bean.get(_property));
                    }else{
                        _tempBean.set(copy2Propertys[_i], null);
                    }
                }
            }         
        }     
        return _tempBean;
    }    
    /**
     * 將_bean的屬性複製到的2bean 如果有資料則覆蓋 但型別必須保持一致
     *
     * @param _bean         複製的物件
     * @param copyPropertys 複製某些屬性
     * @param copy2Propertys複製為對應屬性
     * @return
     */
    public static DynaBean copy2Bean(DynaBean _bean,DynaBean _tempBean ,String[] copyPropertys,String[] copy2Propertys){       
        String _tempStr = getPropertyStr(_bean);
        if(copy2Propertys!=null&&copyPropertys.length!=copy2Propertys.length){
            System.out.println("複製屬性與複製到的屬性不匹配!");
        }else{
            String _property = null;
            if(copy2Propertys==null){
                for(int _i=0;_i<copyPropertys.length;_i++){
                    _property = copyPropertys[_i];
                    if(_tempStr.indexOf(_property)!=-1){
                        _tempBean.set(_property, _bean.get(_property));
                    }else{
                        _tempBean.set(_property, null);
                    }
                }
            }else{
                for(int _i=0;_i<copyPropertys.length;_i++){
                    _property = copyPropertys[_i];
                    if(_tempStr.indexOf(_property)!=-1){
                        _tempBean.set(copy2Propertys[_i], _bean.get(_property));
                    }else{
                        _tempBean.set(copy2Propertys[_i], null);
                    }
                }
            }        
        }     
        return _tempBean;
    }
    /**
     * 複製生成新的bean
     *
     * @param _bean         複製的物件
     * @param copyPropertys 複製某些屬性
     * @param copy2Propertys複製為對應屬性
     * @return
     */
    public static DynaBean copy2Bean(DynaBean _bean,DynaBean _temp2Bean ,String[] copyPropertys){
        return copy2Bean( _bean, _temp2Bean , copyPropertys, null);
    }
    /**
     * 複製生成新的bean
     *
     * @param _bean         複製的物件
     * @param copyPropertys 複製某些屬性
     * @return
     */
    public static DynaBean copyBean(DynaBean _bean,String[] copyPropertys){        
        return copyBean(_bean, copyPropertys,null);
    }    
    private static String getPropertyStr(DynaBean _dynaBean){
        DynaProperty[] _dynaPropertys = _dynaBean.getDynaClass().getDynaProperties();
        StringBuffer _buffer = new StringBuffer(",");
        for(DynaProperty _dynaProperty: _dynaPropertys){
            _buffer.append(_dynaProperty.getName()+",");
        }
        return _buffer.toString();
    }
}

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<DynaBean> 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<DynaBean> 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<DynaBean> getData() {
        return data;
    }
    public void setData(List<DynaBean> 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<PoiTitleBean> inikPoiTitleBean(int _start, String[] _titles){
        List<PoiTitleBean> _poiTitleBeanList = new ArrayList<PoiTitleBean>();
        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<List<String>> 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<List<String>> data,String frompath , int columnstart, int rowstart) throws IOException
    {
        return wirte(data, frompath , UUIDToolsUtil.getUUID(EXCEL_SUB) ,  columnstart,  rowstart);
    }
    
    private static void  wirte(List<List<String>> 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 <rowCount; _i++) {
                   
                   Row _row = sheet.getRow(_i);
                  
                   List<String> _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 <columnCount; _j++) {
                       Cell cell = _row.getCell(_j);
                       if(cell==null){
                           cell = _row.createCell(_j);
                       }
                       cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                       cell.setCellValue(_i_data.get(j));
                       j++;
                   }
                   i++;
               }
               
               FileOutputStream out=new FileOutputStream(topath);
               
               wb.write(out);
               out.flush();
               out.close();
            
        } catch (InvalidFormatException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }   
        
    }
    
    private static int getFileCount(int dataSize){

        int fileCount = (dataSize%EXCELMAXCOUNT==0?dataSize:(dataSize-dataSize%EXCELMAXCOUNT+EXCELMAXCOUNT))/EXCELMAXCOUNT;
        
        return fileCount;
    }
    /**
     * @descri 使用該方法進行excel匯出
     * @param frompath    模板路徑
     * @param filename  檔名稱
     * @param _poiDataBean    資料
     * @param _poiTitleBean 標題
     * @return
     * @throws IOException
     * @throws RowsExceededException
     * @throws WriteException
     */
    public static void  wirte(String frompath ,String filename, PoiDataBean _poiDataBean, List<PoiTitleBean> _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> _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<DynaBean> 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<Integer,CellStyle > _callTypeMap0 = new HashMap<Integer,CellStyle >();
                 Cell cell = _row.getCell(_poiDataBean.getColumnstart());

                  for(int _j = columnstart; _j <columnCount; _j++){
                      _cell = _row.getCell(_j);
                      if(_cell!=null){
                          _callTypeMap0.put(_j,  _cell.getCellStyle());
                      }else{
                          _callTypeMap0.put(_j,  cell.getCellStyle());
                      }
                  }
                
                 _row = sheet.getRow(_poiDataBean.getRowstart()+1);
                  Map<Integer,CellStyle > _callTypeMap1 = new HashMap<Integer,CellStyle >();
                  cell = _row.getCell(_poiDataBean.getColumnstart());

                  for(int _j = columnstart; _j <columnCount; _j++){
                      _cell = _row.getCell(_j);
                      if(_cell!=null){
                          _callTypeMap1.put(_j,  _cell.getCellStyle());
                      }else{
                          _callTypeMap1.put(_j,  cell.getCellStyle());
                      }
                  }
                
                short _rowHeight = _row.getHeight();
                if(!_poiDataBean.isTieleWirte()){
                    if(_poiTitleBean != null && _poiTitleBean.size()>0){
                        
                        for(PoiTitleBean _title : _poiTitleBean){
                            _row = sheet.getRow(_title.getRow());
                            cell = _row.getCell(_title.getCall());
                            cell.setCellValue(_title.getTitle());
                        }
                    }
                }
                
                
                 for(int _i = rowStart; _i <rowCount; _i++) {
                       
                       _row = sheet.getRow(_i);
                      
                       DynaBean _i_data=data.get(i);
                       if(_row==null){
                           _row= sheet.createRow(_i);
                       }
                       _row.setHeight(_rowHeight);
                       Map<Integer,CellStyle > _callTypeMap = null;
                       if(_i%2!=0){
                           _callTypeMap = _callTypeMap0;
                       }else{
                           _callTypeMap = _callTypeMap1;
                       }
                       int j = 0;//需要額外的計數
                       for(int _j = columnstart; _j <columnCount; _j++) {
                           cell = _row.getCell(_j);
                           
                           if(cell==null){
                               cell = _row.createCell(_j);
                           }

                           cell.setCellStyle(_callTypeMap.get(_j));
                           dynaBeanVal2CellVal(cell,_i_data.get(columnname[_j-columnstart]));
                           j++;
                       }
                       i++;
                   }
                   
                   wb.write(out);
                
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                out.close();
            }   
        }
    }
    
    public static String encodingFileName(String fileName) {
        String returnFileName = "";
        try {
            returnFileName = new String(fileName.getBytes("GB2312"), "ISO8859-1");
            returnFileName = StringUtils.replace(returnFileName, "+", "%20");
                
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            
        }
        return returnFileName;
    }
    
    private static void dynaBeanVal2CellVal(Cell cell,Object _dynaBeanVal){

        if(_dynaBeanVal instanceof String){
            cell.setCellValue(Util.toString(_dynaBeanVal));
        }else if(_dynaBeanVal instanceof Date){
            cell.setCellValue((Date)_dynaBeanVal);
        }else if(_dynaBeanVal instanceof Boolean){
            cell.setCellValue((Boolean)_dynaBeanVal);
        }else if(_dynaBeanVal instanceof Integer ){
            cell.setCellValue((Integer)_dynaBeanVal);
        }else if(_dynaBeanVal instanceof Float ){
            cell.setCellValue((Float)_dynaBeanVal);
        }else if(_dynaBeanVal instanceof Double ){
            cell.setCellValue((Double)_dynaBeanVal);
        }else {
            cell.setCellValue(Util.toString(_dynaBeanVal));
        }
    }
    /**
     *
     * @param _excelPath     Excel檔案路徑
     * @param _picPath        圖片路徑
     * @param columnstart    從第幾列開始
     * @param rowstart        從第幾行開始
     * @param columnCount    佔用幾列
     * @param rowCount        佔用幾行
     *
     *  rowstart<0 則會自動追加在最後 |rowstart|行
     *
     * @return
     * @throws IOException
     * @throws RowsExceededException
     * @throws WriteException
     */
    public static boolean  wirtePic(String _excelPath , ExcelPicBean _excelPicBean) throws IOException{
        
        String _picPath = _excelPicBean.getPicPath();
        int columnstart = _excelPicBean.getColumnstart();
        int rowstart = _excelPicBean.getRowstart();
        int columnCount = _excelPicBean.getColumnCount();
        int rowCount = _excelPicBean.getRowCount();
        
        Workbook wb = null;
        InputStream inp = new FileInputStream(_excelPath);
        ByteArrayOutputStream byteArrayOut = null;
        FileOutputStream out = null;
        
        int PICTURE_TYPE = 0;
        
        try {
            
            wb = WorkbookFactory.create(inp);
            File pic = new File(_picPath);
            String filename = pic.getName();
            String sux = filename.substring(filename.lastIndexOf(".")+1, filename.length()).toLowerCase();

            if("png".equals(sux)){
                PICTURE_TYPE = Workbook.PICTURE_TYPE_PNG;
            }else if("jpg".equals(sux)){
                PICTURE_TYPE = Workbook.PICTURE_TYPE_JPEG;
            }
        //先把讀進來的圖片放到一個ByteArrayOutputStream中,以便產生ByteArray
        byteArrayOut = new ByteArrayOutputStream();
        BufferedImage bufferImg = ImageIO.read(new File(_picPath));
        
        ImageIO.write(bufferImg,"png",byteArrayOut);
        //建立工作薄

        Sheet sheet = wb.getSheetAt(0);
        
        if(rowstart<0){
            
            rowstart = sheet.getLastRowNum()-rowstart;
        }
        
        
        Drawing patriarch = sheet.createDrawingPatriarch();
        ClientAnchor anchor = patriarch.createAnchor(
                10,10,10,10,
                columnstart            ,  rowstart,
                columnstart+columnCount,rowstart+rowCount);

        patriarch.createPicture(anchor , wb.addPicture(byteArrayOut.toByteArray(),PICTURE_TYPE));

//        引數說明:
//        row  起始行 cell 起始單元格  row1 終止行  cell2 終止單元格
            if(inp!=null){
                inp.close();
            }
            out = new FileOutputStream(_excelPath);
            wb.write(out);
            out.flush();
            out.close();
        
        }catch(Exception e){
            e.printStackTrace();
            return false;
        }finally{
            if(inp!=null){
                inp.close();
            }
            if(out!=null){
                out.close();
            }
            if(byteArrayOut!=null){
                byteArrayOut.close();
            }
            
        }
        return true;
    }
}

Excel模板檔案 studentGrade.xlsx excel模板 實現效果 studentname引數為空的情況 瀏覽器位址列 地址1 回車 彈框1 匯出的資料 表1 studentname引數不為空的情況 瀏覽器位址列 地址2 匯出的資料 表2 至此,匯出規則的excel就搞定了