這是Excel類對Excel的部分操作
public HSSFWorkbook exportExcel(String title ,Map<String, String> headers, List<Map<String, Object>> dataBase) {
sheet = workbook.getSheetAt(0); // 預設的 第0個工作簿
int i = 0;
Map<String, Integer> cellAt = new HashMap<>();
row = sheet.createRow(0);
for (Map.Entry<String, String> map : headers.entrySet()) {
String key = map.getKey();
cell = row.createCell(i);
cell.setCellValue(map.getValue());
cellAt.put(key, i);
i++;
}
for (int j = 0; j < dataBase.size(); j++) {
row = sheet.createRow(j + 1);
for (Map.Entry<String, Integer> mapd : cellAt.entrySet()) {
Integer value = mapd.getValue();
String key = mapd.getKey();
cell = row.createCell(value);
Map<String, Object> dataBadeMap = dataBase.get(j);
Object dataBadeMapValue = dataBadeMap.get(key);
String dataBadeMapValueToString = dataBadeMapValue != null ? dataBadeMapValue.toString() : "";
cell.setCellValue(dataBadeMapValueToString);
}
}
HttpServletResponse response = Noxa.instance.getNoxaDispatcher().getResponse();
try(OutputStream out = response.getOutputStream();){
response.reset();
response.setContentType("application/x-download");//告訴浏覽器你要下載下傳東西才能彈出下載下傳框讓你選擇下載下傳路徑
response.addHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(title+".xls", "UTF-8"));
workbook.write(out);
if(log.isInfoEnabled()){
log.info("導出成功");
}
out.flush();
} catch (Exception e) {
log.error("導出失敗");
}
return workbook;
}
----------這一塊是下載下傳到伺服器本地的
/*try {
FileOutputStream os = new FileOutputStream("D://upload//"+title+".xls");
workbook.write(os);
os.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return workbook;
}
*/
----------
這裡有個問題就是你通過Ajax來請求浏覽器是不理你的,但是背景資料是有的,也照樣有傳回。但是浏覽器就是不理你,我也不知道問題在哪,希望哪個大神可以指點一下。不過在界面上我們可以通過a标簽的href屬性來請求,或者通過form表單來送出。
第一次寫。多指教