整體流程
- Action 方法設定檔名編碼並回傳
success。
getInputStream() 產生 Excel 二進位串流。
struts.xml 配置 stream 結果型別,指定 MIME、檔名、串流來源。
- 前端按鈕直接連結 Action URL 觸發下載。
1. Action 類別
public class ActiveCountAction extends ActionSupport {
private String fileName;
private InputStream inputStream;
public String exportActiveExcel() {
String name = "活躍度列表.xls";
try {
name = URLEncoder.encode(name, "UTF-8");
fileName = new String(name.getBytes(), "ISO-8859-1");
} catch (UnsupportedEncodingException e) { e.printStackTrace(); }
return SUCCESS;
}
public InputStream getInputStream() {
ExportExcel ex = new ExportExcel();
String[] headers = {"學號", "姓名", "年齡", "性別", "出生日期"};
JSONArray data = new JSONArray();
// 填充測試資料...
return ex.exportExcel("活躍度分析", headers, data);
}
// getter/setter 略...
}
2. Excel 產生工具類
public class ExportExcel {
public InputStream exportExcel(String title, String[] headers, JSONArray array) {
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet(title);
sheet.setDefaultColumnWidth(30);
// 樣式與字體設定略...
// 標題列
HSSFRow row = sheet.createRow(0);
for (int i = 0; i < headers.length; i++) {
HSSFCell cell = row.createCell(i);
cell.setCellStyle(titleStyle);
cell.setCellValue(new HSSFRichTextString(headers[i]));
}
// 資料列
for (int i = 0; i < array.size(); i++) {
row = sheet.createRow(i + 1);
JSONArray arr = array.getJSONArray(i);
for (int j = 0; j < arr.size(); j++) {
HSSFCell cell = row.createCell(j);
cell.setCellStyle(contentStyle);
HSSFRichTextString txt = new HSSFRichTextString(arr.get(j).toString());
txt.applyFont(contentFont); // 藍色字體
cell.setCellValue(txt);
}
}
// 寫入 ByteArrayOutputStream
ByteArrayOutputStream baos = new ByteArrayOutputStream();
wb.write(baos);
byte[] bytes = baos.toByteArray();
try { baos.close(); } catch (IOException ignored) {}
return new ByteArrayInputStream(bytes);
}
}
3. struts.xml 配置
application/vnd.ms-excel
attachment;filename="${fileName}"
inputStream
4096
4. 前端呼叫
關鍵注意事項
inputName 對應 Action 的 getInputStream() 方法(去掉 get 首字小寫)。
- 檔名編碼雙重處理(UTF-8 → ISO-8859-1)解決中文檔名亂碼。
- 使用
ByteArrayInputStream 避免臨時檔案 I/O。
- POI 版本需與專案相容,HSSF 為 .xls,XSSF 為 .xlsx。