問題描述:
對於不同瀏覽器存在對中文編碼格式問題,從而在導出Excel文件時,中文文件名出現亂碼的情況,即在程序中給要導出的文件指定一個中文名字時,在瀏覽器上出現的下載框中的文件名出現了亂碼,解決如下:
解決方案:
- Date dt=new Date();//如果不需要格式,可直接用dt,dt就是當前系統時間
- DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");//設置顯示格式
- String nowTime="";
- nowTime= df.format(dt);//用DateFormat的format()方法在dt中獲取並以yyyy/MM/dd HH:mm:ss格式顯示
- WritableWorkbook book = null;
- String fileName = null;
- fileName = "中文文件名"+nowTime+ ".xls";
- OutputStream os = null;
- final String userAgent = request.getHeader("USER-AGENT");
- try {
- os = response.getOutputStream();
- esponse.reset();//清空輸出流
- String finalFileName = null;
- if(StringUtils.contains(userAgent, "MSIE")){//IE瀏覽器
- finalFileName = URLEncoder.encode(fileName,"UTF8");
- }else if(StringUtils.contains(userAgent, "Mozilla")){//google,火狐瀏覽器
- finalFileName = new String(fileName.getBytes(), "ISO8859-1");
- }else{
- finalFileName = URLEncoder.encode(fileName,"UTF8");//其他瀏覽器
- }
- response.setHeader("Content-Disposition", "attachment; filename=\"" + finalFileName + "\"");//這里設置一下讓瀏覽器彈出下載提示框,而不是直接在瀏覽器中打開
- response.setContentType("application/vnd.ms-excel");
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- }catch (IOException e) {
- e.printStackTrace();
- }
- book = Workbook.createWorkbook(os);
- WritableSheet sheet = book.createSheet("Sheet_1", 0);.................................