java中如何使用POI來實現導出excel功能

題記:excel的導入導出是在後面管理經常用到的功能,每每實現有兩種方法,用jxl或者poi,均可以的,他倆區別不大,這裏主要寫Poi如何實現。java

一:

頁面預覽

20170106105210648.png

點擊導出按鈕,會下載個excel,打開web

20170106105301539.png

說明:這裏是將全部導出了,我也能夠根據條件來導出spring

20170106105346914.png

點擊導出按鈕,會下載個excel,打開apache

20170106105422673.png

二:實現代碼

這裏我把主要代碼提出來 user_list.jspapp

<td style="vertical-align:top;"><a class="btn btn-mini btn-light" onclick="toExcel();" title="導出到EXCEL"><i id="nav-search-icon" class="icon-download-alt"></i></a></td>

user.jswebapp

//導出excel  
function toExcel(){  
    var USERNAME = $("#nav-search-input").val();  
    var lastLoginStart = $("#lastLoginStart").val();  
    var lastLoginEnd = $("#lastLoginEnd").val();  
    var ROLE_ID = $("#role_id").val();  
    window.location.href='<%=basePath%>user/excel.do?USERNAME='+USERNAME+'&lastLoginStart='+lastLoginStart+'&lastLoginEnd='+lastLoginEnd+'&ROLE_ID='+ROLE_ID;  
}

UserController:jsp

/* 
     * 導出用戶信息到EXCEL 
     * @return 
     */  
    @RequestMapping(value="/excel")  
    public ModelAndView exportExcel(){  
        ModelAndView mv = this.getModelAndView();  
        PageData pd = new PageData();  
        pd = this.getPageData();  
        try{  
            if(Jurisdiction.buttonJurisdiction(menuUrl, "cha")){  
                //檢索條件===  
                String USERNAME = pd.getString("USERNAME");  
                if(null != USERNAME && !"".equals(USERNAME)){  
                    USERNAME = USERNAME.trim();  
                    pd.put("USERNAME", USERNAME);  
                }  
                String lastLoginStart = pd.getString("lastLoginStart");  
                String lastLoginEnd = pd.getString("lastLoginEnd");  
                if(lastLoginStart != null && !"".equals(lastLoginStart)){  
                    lastLoginStart = lastLoginStart+" 00:00:00";  
                    pd.put("lastLoginStart", lastLoginStart);  
                }  
                if(lastLoginEnd != null && !"".equals(lastLoginEnd)){  
                    lastLoginEnd = lastLoginEnd+" 00:00:00";  
                    pd.put("lastLoginEnd", lastLoginEnd);  
                }   
                //檢索條件===  
                  
                Map<String,Object> dataMap = new HashMap<String,Object>();  
                List<String> titles = new ArrayList<String>();  
                  
                titles.add("用戶名");      //1  
                titles.add("編號");       //2  
                titles.add("姓名");           //3  
                titles.add("職位");           //4  
                titles.add("手機");           //5  
                titles.add("郵箱");           //6  
                titles.add("最近登陸");     //7  
                titles.add("上次登陸IP");   //8  
                  
                dataMap.put("titles", titles);  
                  
                List<PageData> userList = userService.listAllUser(pd);  
                List<PageData> varList = new ArrayList<PageData>();  
                for(int i=0;i<userList.size();i++){  
                    PageData vpd = new PageData();  
                    vpd.put("var1", userList.get(i).getString("USERNAME"));     //1  
                    vpd.put("var2", userList.get(i).getString("NUMBER"));       //2  
                    vpd.put("var3", userList.get(i).getString("NAME"));         //3  
                    vpd.put("var4", userList.get(i).getString("ROLE_NAME"));    //4  
                    vpd.put("var5", userList.get(i).getString("PHONE"));        //5  
                    vpd.put("var6", userList.get(i).getString("EMAIL"));        //6  
                    vpd.put("var7", userList.get(i).getString("LAST_LOGIN"));   //7  
                    vpd.put("var8", userList.get(i).getString("IP"));           //8  
                    varList.add(vpd);  
                }  
                dataMap.put("varList", varList);  
                ObjectExcelView erv = new ObjectExcelView();                    //執行excel操做  
                mv = new ModelAndView(erv,dataMap);  
            }  
        } catch(Exception e){  
            logger.error(e.toString(), e);  
        }  
        return mv;  
    }

ObjectExcelViewmaven

package com.fh.util;  
  
import java.util.Date;  
import java.util.List;  
import java.util.Map;  
  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
  
import org.apache.poi.hssf.usermodel.HSSFCell;  
import org.apache.poi.hssf.usermodel.HSSFCellStyle;  
import org.apache.poi.hssf.usermodel.HSSFFont;  
import org.apache.poi.hssf.usermodel.HSSFSheet;  
import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
import org.springframework.web.servlet.view.document.AbstractExcelView;  
  
import com.fh.util.PageData;  
import com.fh.util.Tools;  
/** 
* 導入到EXCEL 
* 類名稱:ObjectExcelView.java 
* @version 1.0 
 */  
public class ObjectExcelView extends AbstractExcelView{  
  
    @Override  
    protected void buildExcelDocument(Map<String, Object> model,  
            HSSFWorkbook workbook, HttpServletRequest request,  
            HttpServletResponse response) throws Exception {  
        // TODO Auto-generated method stub  
        Date date = new Date();  
        String filename = Tools.date2Str(date, "yyyyMMddHHmmss");  
        HSSFSheet sheet;  
        HSSFCell cell;  
        response.setContentType("application/octet-stream");  
        response.setHeader("Content-Disposition", "attachment;filename="+filename+".xls");  
        sheet = workbook.createSheet("sheet1");  
          
        List<String> titles = (List<String>) model.get("titles");  
        int len = titles.size();  
        HSSFCellStyle headerStyle = workbook.createCellStyle(); //標題樣式  
        headerStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);  
        headerStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);  
        HSSFFont headerFont = workbook.createFont();    //標題字體  
        headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);  
        headerFont.setFontHeightInPoints((short)11);  
        headerStyle.setFont(headerFont);  
        short width = 20,height=25*20;  
        sheet.setDefaultColumnWidth(width);  
        for(int i=0; i<len; i++){ //設置標題  
            String title = titles.get(i);  
            cell = getCell(sheet, 0, i);  
            cell.setCellStyle(headerStyle);  
            setText(cell,title);  
        }  
        sheet.getRow(0).setHeight(height);  
          
        HSSFCellStyle contentStyle = workbook.createCellStyle(); //內容樣式  
        contentStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);  
        List<PageData> varList = (List<PageData>) model.get("varList");  
        int varCount = varList.size();  
        for(int i=0; i<varCount; i++){  
            PageData vpd = varList.get(i);  
            for(int j=0;j<len;j++){  
                String varstr = vpd.getString("var"+(j+1)) != null ? vpd.getString("var"+(j+1)) : "";  
                cell = getCell(sheet, i+1, j);  
                cell.setCellStyle(contentStyle);  
                setText(cell,varstr);  
            }  
              
        }  
          
    }  
  
}

maven的pom.xml如何引入poi的jar包ide

<span style="white-space:pre">      </span><!-- poi-3.11-20141221 -->  
        <dependency>  
            <groupId>poi</groupId>  
            <artifactId>poi   </artifactId>  
            <version>1.0</version>  
            <scope>system</scope>  
            <systemPath>${project.basedir}/src/main/webapp/WEB-INF/lib/poi-3.11-20141221.jar</systemPath>  
        </dependency>  
        <!-- poi-examples-3.11-20141221 -->  
        <dependency>  
            <groupId>poi-examples</groupId>  
            <artifactId>poi-examples</artifactId>  
            <version>1.0</version>  
            <scope>system</scope>  
            <systemPath>${project.basedir}/src/main/webapp/WEB-INF/lib/poi-examples-3.11-20141221.jar</systemPath>  
        </dependency>  
        <!--poi-excelant-3.11-20141221 -->  
        <dependency>  
            <groupId>poi-excelant</groupId>  
            <artifactId>poi-excelant</artifactId>  
            <version>1.0</version>  
            <scope>system</scope>  
            <systemPath>${project.basedir}/src/main/webapp/WEB-INF/lib/poi-excelant-3.11-20141221.jar</systemPath>  
        </dependency>  
        <!--poi-ooxml-3.11-20141221 -->  
        <dependency>  
            <groupId>poi-ooxml</groupId>  
            <artifactId>poi-ooxml</artifactId>  
            <version>1.0</version>  
            <scope>system</scope>  
            <systemPath>${project.basedir}/src/main/webapp/WEB-INF/lib/poi-ooxml-3.11-20141221.jar</systemPath>  
        </dependency>  
        <!-- poi-ooxml-schemas-3.11-20141221 -->  
        <dependency>  
            <groupId>poi-ooxml-schemas</groupId>  
            <artifactId>poi-ooxml-schemas</artifactId>  
            <version>1.0</version>  
            <scope>system</scope>  
            <systemPath>${project.basedir}/src/main/webapp/WEB-INF/lib/poi-ooxml-schemas-3.11-20141221.jar</systemPath>  
        </dependency>  
        <!-- poi-scratchpad-3.11-20141221 -->  
        <dependency>  
            <groupId>poi-scratchpad</groupId>  
            <artifactId>poi-scratchpad</artifactId>  
            <version>1.0</version>  
            <scope>system</scope>  
            <systemPath>${project.basedir}/src/main/webapp/WEB-INF/lib/poi-scratchpad-3.11-20141221.jar</systemPath>  
        </dependency>
相關文章
相關標籤/搜索