美文网首页
spring mvc Ajax下载excel

spring mvc Ajax下载excel

作者: 慢狍子 | 来源:发表于2016-11-17 16:28 被阅读1883次

    spring mvc Ajax下载excel

    必要条件

    1. spring mvc
    2. jquery
    3. FileSaver
    

    mvc代码

    import com.tw.study.springboot.entity.Excel;
    import org.apache.poi.ss.usermodel.Cell;
    import org.apache.poi.ss.usermodel.Row;
    import org.apache.poi.ss.usermodel.Sheet;
    import org.springframework.web.servlet.ModelAndView;
    import org.springframework.web.servlet.view.document.AbstractXlsView;
    import javax.servlet.http.HttpServletRequest;

    import javax.servlet.http.HttpServletResponse;
    import java.io.FileOutputStream;
    import java.util.Collection;
    import java.util.Map;

    /**

    • Created by hwwei on 2016/11/16.
      */
      public class ExcelView extends AbstractXlsView {

      static final String KEY_EXCEL_DATA = "KEY_EXCEL_DATA";

      public static final ModelAndView newModelAndView(Object data) {
      ModelAndView modelAndView = new ModelAndView(INSTANCE);
      modelAndView.addObject(KEY_EXCEL_DATA, data);
      return modelAndView;
      }

      private static ExcelView INSTANCE = new ExcelView();

      @Override
      protected void buildExcelDocument(Map<String, Object> model,
      org.apache.poi.ss.usermodel.Workbook workbook,
      HttpServletRequest request,
      HttpServletResponse response) throws Exception {

        Object data = model.get(KEY_EXCEL_DATA);
        if (!(data instanceof Collection)) {
            throw new IllegalArgumentException("类型不匹配");
        }
        Collection<?> list = (Collection<?>) data;
    
        // 行下标
        int rowIndex = 0;
    
        Sheet sheet = workbook.createSheet();
        Row row = sheet.createRow(rowIndex++);
        Cell nameCell = row.createCell(0);
        nameCell.setCellValue("名字");
        Cell ageCell = row.createCell(1);
        ageCell.setCellValue("年龄");
        Cell oldCell = row.createCell(2);
        oldCell.setCellValue("老么");
    
        for (Object o : list) {
            Excel item = (Excel) o;
            Row itemRow = sheet.createRow(rowIndex++);
    
            nameCell = itemRow.createCell(0);
            nameCell.setCellValue(item.name);
    
            ageCell = itemRow.createCell(1);
            ageCell.setCellValue(item.age);
    
            oldCell = itemRow.createCell(2);
            oldCell.setCellValue(item.old);
        }
        FileOutputStream stream = new FileOutputStream("/Users/hwwei/Downloads/tmp.xlsx");
        workbook.write(stream);
        stream.flush();
        stream.close();
        response.setHeader("Content-Disposition", "attachment; filename= data.xlsx");
    }
    

    }

    controller
    @Controller
    @RequestMapping("excel")
    public class ExcelDownloadController {
    
        @RequestMapping
        public ModelAndView down() {
    
             List<Excel> content = new ArrayList<>();
            content.add(new Excel("wafer", 1,true));
            return ExcelView.newModelAndView(content == null ? Collections.emptyList() : content);
        }
    }
    

    jquery

         var xhr = new XMLHttpRequest();
    //            xhr.open('POST', 'http://localhost:8080/excel', true);
    //            xhr.responseType = 'blob';
    //
    //            xhr.setRequestHeader('Content-type', 'application/json; charset=utf-8');
    //            xhr.onload = function(e) {
    //                if (this.status == 200) {
    //                    var blob = new Blob([this.response], {type: 'application/vnd.ms-excel'});
    //                    saveAs(blob, "file.xlsx");
    //                } else {
    //                    alert('Unable to download excel.')
    //                }
    //            };
    //            xhr.send(JSON.stringify({}));
    
            $.ajax({
                url: "http://localhost:8080/excel",
                method: "post",
                /**重点在于这一行,设置返回类型,否则浏览器将会以奇怪的方式解析zi'ji**/
                dataType: 'blob',
                success: function(data){
                    var blob = new Blob([data], {type: "application/vnd.ms-excel"});
                    saveAs(blob, "file.xlsx");
                }
            });

    相关文章

      网友评论

          本文标题:spring mvc Ajax下载excel

          本文链接:https://www.haomeiwen.com/subject/hvgdpttx.html