一、准备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中,输出格式一致就可以成功导出了!

 

posted on 2020-06-22 13:21  最美岁月  阅读(4933)  评论(0编辑  收藏  举报