問題是這樣的,我現在想通過下載在用戶在點擊匯出時將查詢的結果匯出來。
然后這是我的js
layer.confirm('確定匯出到Excel?', {
btn : [ '確定', '取消' ]
}, function() {
$.ajax({
type : "POST",
url : "/require/export2Excel",
responseType : Blob,
data : {
requireName : $('#requireName').val(),
requireId : $('#requireId').val(),
functionName : $('#functionName').val(),
functionModule : $('#functionModule').val(),
functionType : $('#functionType').val(),
assignState : $('#assignState').val(),
submitState : $('#submitState').val(),
},success: (wb) => {//wb為我后端的workbook,我寫成respong時excel檔案直接沒資料,寫成這個的時候有資料,這兒可能有問題
var blob = new Blob([wb]); //創建一個blob物件
var a = document.createElement('a'); //創建一個<a></a>標簽
a.href = URL.createObjectURL(blob); // response is a blob
a.download = "功能需求表.xlsx";
a.style.display = 'none';
document.body.appendChild(a);
a.click();
a.remove();
layer.msg("匯出成功!");
}
})
});
后端代碼是這樣的
controller
@PostMapping("export2Excel")
@ResponseBody
public void export2Excel(@RequestParam Map<String, Object> params, HttpServletResponse response){
Query query = new Query(params,"");
List<FunctionRequireDO> list = requireService.list(query);
ExcelUtils.writeExcel(response,list,FunctionRequireDO.class);
}
工具類ExcelUtils
public static <T> void writeExcel(HttpServletResponse response, List<T> dataList, Class<T> cls){
Field[] fields = cls.getDeclaredFields();
List<Field> fieldList = Arrays.stream(fields)
.filter(field -> {
ExcelColumn annotation = field.getAnnotation(ExcelColumn.class);
if (annotation != null && annotation.col() > 0) {
field.setAccessible(true);
return true;
}
return false;
}).sorted(Comparator.comparing(field -> {
int col = 0;
ExcelColumn annotation = field.getAnnotation(ExcelColumn.class);
if (annotation != null) {
col = annotation.col();
}
return col;
})).collect(Collectors.toList());
Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet("Sheet1");
AtomicInteger ai = new AtomicInteger();
{
Row row = sheet.createRow(ai.getAndIncrement());
AtomicInteger aj = new AtomicInteger();
//寫入頭部
fieldList.forEach(field -> {
ExcelColumn annotation = field.getAnnotation(ExcelColumn.class);
String columnName = "";
if (annotation != null) {
columnName = annotation.value();
}
Cell cell = row.createCell(aj.getAndIncrement());
CellStyle cellStyle = wb.createCellStyle();
cellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
cellStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
cellStyle.setAlignment(CellStyle.ALIGN_CENTER);
Font font = wb.createFont();
font.setBoldweight(Font.BOLDWEIGHT_NORMAL);
cellStyle.setFont(font);
cell.setCellStyle(cellStyle);
cell.setCellValue(columnName);
});
}
if (CollectionUtils.isNotEmpty(dataList)) {
dataList.forEach(t -> {
Row row1 = sheet.createRow(ai.getAndIncrement());
AtomicInteger aj = new AtomicInteger();
fieldList.forEach(field -> {
Class<?> type = field.getType();
Object value = "";
try {
value = field.get(t);
} catch (Exception e) {
e.printStackTrace();
}
Cell cell = row1.createCell(aj.getAndIncrement());
if (value != null) {
if (type == Date.class) {
cell.setCellValue(value.toString());
} else {
cell.setCellValue(value.toString());
}
cell.setCellValue(value.toString());
}
});
});
}
//凍結窗格
wb.getSheet("Sheet1").createFreezePane(0, 1, 0, 1);
//瀏覽器下載excel
buildExcelDocument("功能需求表.xlsx",wb,response);
//生成excel檔案
// buildExcelFile("C:/Users/Administrator/Desktop/"+fileName+".xlsx",wb);
}
/**
* 瀏覽器下載excel
* @param fileName
* @param wb
* @param response
*/
private static void buildExcelDocument(String fileName, Workbook wb, HttpServletResponse response){
try {
//application/octet-stream
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
response.setHeader("content-type", "application/vnd.ms-excel;charset=UTF-8");
response.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(fileName, "utf-8"));
response.flushBuffer();
wb.write(response.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
我現在這樣寫可以匯出來一個excel檔案,但是打開的時候顯示

還有一種方式就是我可以不用下載,直接在后端生成,但是這樣目錄我又就寫死了,感覺對用戶的友好性不好。。。大佬們幫幫我吧,,,畢設寫的我快瘋了
uj5u.com熱心網友回復:
1、前端別用post,改用打開新視窗2、后端改用get請求,引入 import cn.hutool.core.*
@GetMapping("/export")
@ApiOperation(value = "匯出",httpMethod = "GET")
public void test3( FeedbackListParam param, HttpServletResponse response) {
ExcelWriter writer = ExcelUtil.getWriter();
try {
/**
*/
String head = "匯出資料";
List<List<Object>> rows = new LinkedList<>();
//填充rows
List<String> rowHead = CollUtil.newArrayList("id", "用戶id", "用戶昵稱");
writer.writeHeadRow(rowHead);
writer.write(rows);
//設定寬度自適應
writer.setColumnWidth(-1, 22);
//response為HttpServletResponse物件
response.setContentType("application/vnd.ms-excel;charset=utf-8");
//test.xls是彈出下載對話框的檔案名,不能為中文,中文請自行編碼
response.setHeader("Content-Disposition", "attachment;filename=" + new String((head).getBytes("UTF-8"), "ISO-8859-1") + ".xls");
ServletOutputStream out = response.getOutputStream();
//out為OutputStream,需要寫出到的目標流
writer.flush(out);
} catch (Exception e) {
log.error("匯出例外",e);
e.printStackTrace();
} finally {
// 關閉writer,釋放記憶體
writer.close();
}
}
uj5u.com熱心網友回復:
我改成了get,沒改呼叫的類,沒用啊
uj5u.com熱心網友回復:
我寫個測驗類試下你給的這個類吧。。
uj5u.com熱心網友回復:
不好使啊老哥轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/252859.html
標籤:Java SE
