匯出txt檔案的工具類
阿新 • • 發佈:2021-02-10
匯出txt文件
學習地址:https://www.cnblogs.com/godtrue/p/6879594.html
@GetMapping("/{id}/export")
@ApiOperation("下載txt文件")
public void exportText(HttpServletResponse response, @PathVariable(value = "id") @ApiParam(value = "主鍵id", example = "1", required = true) Integer id) {
String jsonString = "2223";
ExportTextUtil.writeToTxt(response, jsonString, "zsw");
}
工具類
/**
* 匯出檔案檔案的工具類
*/
@Slf4j
public class ExportTextUtil {
/**
* 匯出文字檔案
*
* @param response
* @param jsonString
* @param fileName
*/
public static void writeToTxt(HttpServletResponse response, String jsonString, String fileName) {//設定響應的字符集
response.setCharacterEncoding("utf-8");
response.setContentType("text/plain");
response.addHeader(
"Content-Disposition" ,
"attachment; filename="
+ FileUtil.genAttachmentFileName(fileName + "_", "ZSW")
+ MessageFormat.format("{0,date,yyyy-MM-dd}", new Object[]{Calendar.getInstance().getTime()})
+ ".txt");//通過後綴可以下載不同的檔案格式
BufferedOutputStream buff = null;
ServletOutputStream outStr = null;
try {
outStr = response.getOutputStream();
buff = new BufferedOutputStream(outStr);
buff.write(delNull(jsonString).getBytes("UTF-8"));
buff.flush();
buff.close();
} catch (Exception e) {
log.error("匯出檔案檔案出錯,e:{}", e);
} finally {
try {
buff.close();
outStr.close();
} catch (Exception e) {
log.error("關閉流物件出錯 e:{}", e);
}
}
}
/**
* 如果字串物件為 null,則返回空字串,否則返回去掉字串前後空格的字串
*
* @param str
* @return
*/
public static String delNull(String str) {
String returnStr = "";
if (StringUtils.isNotBlank(str)) {
returnStr = str.trim();
}
return returnStr;
}
}
@Slf4j
public class FileUtil {
public static void writeCsv(HttpServletResponse httpServletResponse, String fileName, List<String> header, List<List<String>> columns) {
httpServletResponse.setContentType("application/octet-stream;charset=utf-8");
httpServletResponse.setHeader("Content-Disposition", "attachment; filename=\"" + URLUtil.encode(fileName, "UTF-8") + "\"");
List<List<String>> rowList = new ArrayList<>();
rowList.add(header);
rowList.addAll(columns);
final CsvWriter writer;
try {
writer = CsvUtil.getWriter(httpServletResponse.getWriter());
} catch (IOException e) {
log.error("IO error", e);
throw new CustomizeException(BaseResultCode.FAIL_IO);
}
writer.write(rowList);
}
/**
* 生成匯出附件中文名。應對匯出檔案中文亂碼
* <p>
* response.addHeader("Content-Disposition", "attachment; filename=" + cnName);
*
* @param cnName
* @param defaultName
* @return
*/
public static String genAttachmentFileName(String cnName, String defaultName) {
try {
cnName = new String(cnName.getBytes("gb2312"), "ISO8859-1");
} catch (Exception e) {
cnName = defaultName;
}
return cnName;
}
}