跳到主要內容

JSP環境示範 Java 產生文字檔(CSV為例)

這個例子示範 Java 產出可以提供下載的文字檔
從本例改出 Servlet 用的版本的作法會更簡單,可以依自己的需求調整
CSV格式是文字檔的其中一種應用,這裡也會示範其中的一些細節

<%@ page import="java.util.LinkedList"%>
<%@ page import="java.net.URLEncoder"%>
<%@ page import="java.io.PrintWriter"%>
<%@ page trimDirectiveWhitespaces="true" %>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
// CSV file name
String fileName = request.getParameter("fn")+".csv";

//output content container
LinkedList<String> outputContent = new LinkedList<String>();

// add CSV title
outputContent.add("Name,Sex,Age");

// add CSV content
outputContent.add("John,M,12");
outputContent.add("Marcus,M,18");

// no caching for download files
response.setHeader("Cache-Control", "no-cache"); //HTTP 1.1
response.setHeader("Pragma", "no-cache"); //HTTP 1.0
response.setDateHeader("Expires", 0);

response.setCharacterEncoding("BIG5");
response.setContentType("application/octet-stream");
String uriencodedFilename = fileName;
try {
    uriencodedFilename = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
} catch (UnsupportedEncodingException e) { }
response.setHeader("Content-Disposition", "attachment;filename*=UTF-8''" + uriencodedFilename + ";filename=\"" + uriencodedFilename + "\"");

PrintWriter printWriter = response.getWriter();
try {
    for(String s : outputContent){
        printWriter.print(s+"\r\n");  // MS format
    }
} finally {
    printWriter.flush();
    printWriter.close();
}
%>

因為還是有不少老舊的系統只吃 ASCII 標準的格式
所以這個例子示範產出BIG5編碼的文字檔案
如果要產出Windows系統下的UTF-8文字檔
修改成 response.setCharacterEncoding("UTF-8")
以及寫入時先寫 printWriter.print('\ufeff');
這行是Windows裡讓系統確定用UTF-8編碼開啟檔案的BOM文字

Content-Disposition 放了不同的 filename 屬性確保下載回來的檔名顯示正確
這也是需要注意的地方

最後寫段JavaScript讓網頁能抓取檔案就OK了

var dlLink = "CSVGen.jsp?fn="+encodeURIComponent(fileName);
window.open(dlLink);

留言