java實現下載並選擇儲存路徑
一、通過瀏覽器提供下載,使檔案直接以流的形式響應客戶端瀏覽器。不多說了,直接上程式碼吧。
public void downloadExcel(HttpServletRequest request,HttpServletResponse response) throws RowsExceededException, WriteException, IOException {
OutputStream os = response.getOutputStream();// 取得輸出流
response.reset();// 清空輸出流
response.setHeader("Content-disposition", "attachment; filename=testRed.xls");// 設定輸出檔案頭
response.setContentType("application/msexcel");// 定義輸出型別
WritableWorkbook wbook = Workbook.createWorkbook(os); // 建立excel檔案
String tmptitle = "測試資料"; // 標題
WritableSheet wsheet = wbook.createSheet(tmptitle, 0); // sheet名稱
// 設定excel標題
WritableFont wfont = new WritableFont(WritableFont.ARIAL, 16, WritableFont.BOLD, false,
UnderlineStyle.NO_UNDERLINE, Colour.BLACK);
WritableCellFormat wcfFC = new WritableCellFormat(wfont);
wcfFC.setBackground(Colour.AQUA);
wsheet.addCell(new Label(1, 0, tmptitle, wcfFC));
wfont = new jxl.write.WritableFont(WritableFont.ARIAL, 14, WritableFont.BOLD, false,
UnderlineStyle.NO_UNDERLINE, Colour.BLACK);
wcfFC = new WritableCellFormat(wfont);
// 開始生成主體內容
wsheet.addCell(new Label(0, 2, "姓名"));
wsheet.addCell(new Label(1, 2, "郵箱"));
// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Map<String, String> map = new HashMap<String, String>();
map.put("Red1", "
map.put("Red2", "[email protected]");
map.put("Red3", "[email protected]");
int count = 0;
for (String key : map.keySet()) {
wsheet.addCell(new Label(0, count + 3, key));
wsheet.addCell(new Label(1, count + 3, map.get(key)));
count++;
}
// 主體內容生成結束
wbook.write(); // 寫入檔案
wbook.close();
os.close(); // 關閉流
}
}
二、在jsp頁面不支援使用ajax,最好使用
window.location.href="後端路徑";的方式