一、准備jar 如下所以放入maven配置文件中

二、controller層

三、SERVICE層


四、CsvUtil文件
/**
* csv文件導入導出
*/
public class CsvUtil {
/**
* 獲取csv文件頭部信息
* @param inputWay 模板文件路徑
* @return
* @throws IOException
*/
public static List<String> getHeader(String inputWay) throws IOException {
List<String> headers = new ArrayList<>();
DataInputStream in = new DataInputStream(new FileInputStream(new File(inputWay)));
BufferedReader br= new BufferedReader(new InputStreamReader(in,"GBK"));
CSVParser parser = CSVFormat.EXCEL.parse(br);
CSVRecord strings = parser.getRecords().get(0);
int size = strings.size();
for (int i = 0; i < size; i++) {
headers.add(strings.get(i));
}
return headers;
}
/**
* 生成csv文件
* @param headers csv文件頭部信息
* @param outputWay 輸出地址
* @param data 填充數據
* @throws IOException
*/
public static void generateCsvFile(List<String> headers, String outputWay, List<List<Object>> data) throws IOException {
FileOutputStream fos = new FileOutputStream(outputWay);
OutputStreamWriter osw = new OutputStreamWriter(fos, "GBK");
String[] toBeStored = headers.toArray(new String[headers.size()]);
CSVFormat csvFormat = CSVFormat.DEFAULT.withHeader(toBeStored);
CSVPrinter csvPrinter = new CSVPrinter(osw, csvFormat);
for (int i = 0; i < data.size(); i++) {//處理掉最后一個版本號
List<Object> singleData = data.get(i);
csvPrinter.printRecord(singleData);
}
csvPrinter.flush();
csvPrinter.close();
}
/**
* 寫出csv文件流
* @param response
* @param inputWay
*/
public static void exportCsvFile(HttpServletResponse response,String inputWay,String fileName) throws IOException {
OutputStream out = response.getOutputStream();
byte[] b = new byte[1024];
File fileLoad = new File(inputWay);
response.reset();
response.setContentType("application/csv");
response.setHeader("content-disposition", "attachment;filename="+ new String((fileName+".csv").getBytes()));
long fileLength = fileLoad.length();
String length1 = String.valueOf(fileLength);
response.setHeader("Content_Length", length1);
FileInputStream in = new FileInputStream(fileLoad);
int n;
while ((n = in.read(b)) != -1) {
out.write(b, 0, n); //每次寫入out1024字節
}
in.close();
out.close();
// 刪除臨時文件
fileLoad.delete();
}
}
五、總結
中間處理業務數據就可以了,放入到保存的list中,輸出格式一致就可以成功導出了!
