Overview of springMVC's ability to download Excel tables

Posted by conspi on Wed, 08 Jul 2020 17:02:44 +0200

spring provides encapsulation classes for Excel DownloadsOrg.springframework.web.Servlet.view.document.AbstractExcelView, when implemented, simply implement a class that inherits AbstractExcelView, then override the

buildExcelDocument(Map<String, Object> model,HSSFWorkbook workbook, HttpServletRequest request,HttpServletResponse response){
}

Method.In the method, use POI to specify the downloaded Excel table.

1. Processing Request Flow

Front End Page Send Request ->Background controller ->controller Gets the data to import Excel, brings in the class that inherits AbstractExcelView in the last returned ModelAndView, and spring fills in the data and returns it to the foreground for download.

2. Overall implementation

Foreground page request:

$.ajax({
                type: "GET",
                url: "history/toExcel",
                data:{account: account, password: password, type: web_type_identifi},
                dataType: "json",
                success: function(data) {
                    if(data.status == "success") {
                    }
                }
            });

Implementation class for AbstractExcelView:

import org.springframework.web.servlet.view.document.AbstractExcelView;
public class ObjectExcelViewHistory extends AbstractExcelView{

    //Style of writing data to Excel that you want to implement
    @Override
    protected void buildExcelDocument(Map<String, Object> model,
            HSSFWorkbook workbook, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
            //Logic for writing data to Excel using POI
            //workbook represents the Excel object to be implemented
            //model is the data obtained from the controller
            }

controller processing:

@Controller
@RequestMapping(value="history")
public class history() {
    private Dao dao;
    @RequestMapping(value="toExcel")
    public ModelAndView historyToExcel() {
        ModelAndView mv = new ModelAndView();
        List<Map> dataMap = dao.findForList();
        ObjectExcelViewHistory erv = new ObjectExcelViewHistory();//Implementation class for AbstractExcelView
        mv = new ModelAndView(erv, dataMap);//Put the implemented AbstractExcelView and the data you want to import into Excel in the constructor of ModelAndView, and leave the rest to spring
        return mv; 
    }
}

After implementing the above three parts, the foreground sends ajax with a similar effect as the following:

For the implementation of POI, see:

Topics: Excel Spring JSON REST