spring mvc Ajax下载excel

2016-11-17  本文已影响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;

/**

    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");
            }
        });
上一篇 下一篇

猜你喜欢

热点阅读