Spring MVC Example: Using Excel view

  For Excel, Spring MVC is recommended to use AbstractXlsView, which implements the view interface, its name may also know that it is just an abstract class and can not generate an instance object. Itself defines an abstract method --buildExcelDocument go to achieve. Other methods of AbstractXlsView Spring has been achieved, so for us to accomplish this method you can use Excel's View feature a
  buildExcelDocument main task is to create a method of Workbook, it is to use the POI API, which we need to download and imported into the project. Where the arguments in the code is also given, has been exported to Excel were a lot of package in the Spring MVC, so many details we do not need to care about.

<!-- poi -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.17</version>
</dependency>

 

  Suppose you want a function to export all the roles of information, but in the future maybe there are other export capabilities. For convenience, first define an interface, this interface is the main custom rules allow developers to generate Excel, as shown in Listing 15-46.
  Listing 15-46: Custom Export Interface Definition

Package com.ssm.chapter15.view; 

Import org.apache.poi.ss.usermodel.Workbook; 

Import a java.util.Map; 

public  interface ExcelExportService { 

    / ** * 
     * exel file generation rules 
     * @param Model Data Model 
     * @ param Workbook Excel Workbook
      * / 
    public  void makeWorkBook (the Map <String, Object> Model, the Workbook Workbook); 

}

 

  With this interface also need to complete an instance of Excel view class --ExcelView, for export purposes also need to download a file name, it also defines a file name (fileName) property, since this view is not a logical view, it is not necessary to be run view resolver, which is defined as shown in Listing 15-47.
  Listing 15-47: Defining Excel view

package com.ssm.chapter15.view;

import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.view.document.AbstractXlsView;

public class ExcelView extends AbstractXlsView {

    //文件名
    private String fileName = null;

    //导出视图自定义接口
    private ExcelExportService excelExpService = null;

    //构造方法1
    public ExcelView(ExcelExportService excelExpService) {
        this.excelExpService = excelExpService;
    }

    //构造方法2
    public ExcelView(String viewName, ExcelExportService excelExpService) {
        this.setBeanName(viewName);
    }

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public ExcelExportService getExcelExpService() {
        return excelExpService;
    } 

    Public  void setExcelExpService (ExcelExportService excelExpService) {
         the this .excelExpService = excelExpService; 
    } 

    @Override 
    protected  void the buildExcelDocument (the Map <String, Object> Model, the Workbook Workbook, the HttpServletRequest Request, the HttpServletResponse Response) throws Exception { 

        // no custom interface 
        IF ( == excelExpService null ) {
             the throw  new new a RuntimeException ( "exporting service interfaces can not !! null" ); 
        } 
        // file name is not empty, an empty string request path is used as the file name 
        IF ! ( StringUtils.isEmpty (fileName)) {

            //Character conversion 
            String reqCharset = request.getCharacterEncoding (); 
            reqCharset = reqCharset == null "UTF-8"? : ReqCharset; 
            fileName = new new String (fileName.getBytes (reqCharset), "ISO8859-1" );
             // set the following filename 
            response.setHeader ( "the Content-Disposition", "Attachment; filename =" + fileName); 
        } 
        // callback interface method used to generate custom Excel document 
        excelExpService.makeWorkBook (Model, Workbook); 
    } 
}

 

  The above method of generating code implements buildExcelDocument of Excel, thus completing a view class. Callback interface method can be customized according to the need of custom rules to generate Excel, then we need new ways to join in the role of the controller, to meet export all the requirements of the role, as shown in Listing 15-48.

  Listing 15-48: Using Excel Export ExcelView

package com.ssm.chapter15.controller;

import com.ssm.chapter15.pojo.PageParams;
import com.ssm.chapter15.pojo.Role;
import com.ssm.chapter15.pojo.RoleParams;
import com.ssm.chapter15.view.ExcelExportService;
import com.ssm.chapter15.view.ExcelView;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
importorg.springframework.web.bind.annotation.RequestMethod;
 Import org.springframework.web.servlet.ModelAndView; 

Import of java.util.ArrayList;
 Import java.util.List;
 Import a java.util.Map; 

@Controller 
@RequestMapping ( " / Excel " )
 public  class ExcelController { 

    @RequestMapping (value =" / Export ", Method = RequestMethod.GET)
     public ModelAndView Export () {
         // model and view 
        ModelAndView = Music Videos new new ModelAndView ();
         // Excel view, and is provided custom export Interface 
        ExcelView EV = new newExcelView (ExportService ());
         // filename 
        ev.setFileName ( "All roles .xlsx" );
         //  // set the SQL back-end parameters
         // RoleParams roleParams = new new RoleParams ();
         //  // limit 10000
         / / PageParams Page PageParams new new = ();
         // page.setStart (0);
         // page.setLimit (10000);
         // roleParams.setPageParams (Page);
         // query
         // List <Role> roleList = roleService.findRoles (roleParams); 
        List <Role> = roleList new new the ArrayList <>  ();
        RoleList.add (new new Role (1L, "shooter", "remote physical output" )); 
        RoleList.add ( new new Role (2L, "Master", "magic output" ));
         // added data model 
        mv.addObject ( "roleList" , roleList); 
        mv.setView (EV); 
        return Music Videos; 
    } 

    @SuppressWarnings ({ "an unchecked" })
     Private ExcelExportService ExportService () {
         // using a Lambda expression custom rules derived excel 
        return (the Map <String, Object> Model, Workbook the Workbook) -> {
             // Get user list 
            list <Role> roleList = (list//);
             Generating Sheet 
            Sheet Sheet = workbook.createSheet ( "all characters" );
             // load title 
            Row title sheet.createRow = (0 ); 
            title.createCell ( 0) .setCellValue ( "No." ); 
            title.createCell ( . 1 ) .setCellValue ( "name" ); 
            title.createCell ( 2) .setCellValue ( "Notes" );
             // convenient list of roles, generate rows of data for ( int i = 0; i <roleList.size (); i ++ ) { 
                Role Role = roleList.get (I);
                 int rowIdx = I +. 1 ;
             
                Row Row = sheet.createRow(rowIdx);
                row.createCell(0).setCellValue(role.getId());
                row.createCell(1).setCellValue(role.getRoleName());
                row.createCell(2).setCellValue(role.getNote());
            }
        };
    }

}

 

  This makes it possible to export Excel, and achieve ExcelExportService interface using Lambda expressions, so Java version 8 and above, the following version of Java 8 may use an anonymous class to achieve it. This uses ExcelExportService interface, you can customize the export rules on its own controller, so that you can develop according to the needs.

Guess you like

Origin www.cnblogs.com/ooo0/p/11109081.html