Spring Boot 匯出csv檔案
阿新 • • 發佈:2019-02-06
1. 匯出檔案工具類
@Slf4j
public class ExportUtil {
/** CSV檔案列分隔符 */
private static final String CSV_COLUMN_SEPARATOR = ",";
/** CSV檔案列分隔符 */
private static final String CSV_RN = "\r\n";
/**
*
* @param dataList 集合資料
* @param colNames 表頭部資料
* @param mapKey 查詢的對應資料
* @param os 返回結果
*/
public static boolean doExport(List<Map<String, Object>> dataList, String colNames, String mapKey, OutputStream os) {
try {
StringBuffer buf = new StringBuffer();
String[] colNamesArr = null;
String[] mapKeyArr = null;
colNamesArr = colNames.split("," );
mapKeyArr = mapKey.split(",");
// 完成資料csv檔案的封裝
// 輸出列頭
for (String aColNamesArr : colNamesArr) {
buf.append(aColNamesArr).append(CSV_COLUMN_SEPARATOR);
}
buf.append(CSV_RN);
if (null != dataList) { // 輸出資料
for (Map<String, Object> aDataList : dataList) {
for (String aMapKeyArr : mapKeyArr) {
buf.append(aDataList.get(aMapKeyArr)).append(CSV_COLUMN_SEPARATOR);
}
buf.append(CSV_RN);
}
}
// 寫出響應
os.write(buf.toString().getBytes("GBK"));
os.flush();
return true;
} catch (Exception e) {
log.error("doExport錯誤...", e);
}
return false;
}
/**
* setHeader
*/
public static void responseSetProperties(String fileName, HttpServletResponse response) throws UnsupportedEncodingException {
// 設定檔案字尾
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String fn = fileName + sdf.format(new Date()) + ".csv";
// 讀取字元編碼
String utf = "UTF-8";
// 設定響應
response.setContentType("application/ms-txt.numberformat:@");
response.setCharacterEncoding(utf);
response.setHeader("Pragma", "public");
response.setHeader("Cache-Control", "max-age=30");
response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fn, utf));
}
}
2.Controller介面
@RestController
@RequestMapping("/test")
@Slf4j
public class DownloadFileController {
@Autowired
private SysLogService sysLogService;
@GetMapping("/file")
public Result download(HttpServletResponse response) {
List<Map<String, Object>> dataList = null;
List<SysLog> logList = sysLogService.findAll();// 查詢到要匯出的資訊
if (logList.size() == 0) {
ResultUtil.failure("無資料匯出");
}
String sTitle = "id,使用者名稱,操作型別,操作方法,建立時間";
String fName = "log_";
String mapKey = "id,username,operation,method,createDate";
dataList = new ArrayList<>();
Map<String, Object> map = null;
for (SysLog order : logList) {
map = new HashMap<>();
map.put("id", order.getId());
map.put("username", order.getUsername());
map.put("operation", order.getOperation());
map.put("method", order.getMethod());
map.put("createDate", DateFormatUtils.format(order.getCreateDate(), "yyyy/MM/dd HH:mm"));
dataList.add(map);
}
try (final OutputStream os = response.getOutputStream()) {
ExportUtil.responseSetProperties(fName, response);
ExportUtil.doExport(dataList, sTitle, mapKey, os);
return null;
} catch (Exception e) {
log.error("生成csv檔案失敗", e);
}
return ResultUtil.failure("資料匯出出錯");
}
}
3.測試
瀏覽器直接請求,可看到檔案下載,Excel可直接開啟檔案。