概述
简单实现
1、页面上传csv解析成数组;
2、后台字符串生成csv文件并在页面输出下载。
IDEA新建的SpringBoot Demo project
html页面:
控制器
package com.example.demo.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@RestController
@RequestMapping("/file")
public class FileController {
/**
* 导入csv文件
* @param file
* @param request
* @param response
* @throws UnsupportedEncodingException
*/
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public void uploadFile(@RequestParam("file") MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
request.setCharacterEncoding("gb2312");
if (file.isEmpty()) {
System.out.println("文件为空");
return;
}
InputStreamReader isr = null;
BufferedReader br = null;
try {
isr = new InputStreamReader(file.getInputStream(), "gb2312");
br = new BufferedReader(isr);
String line = null;
List> list = new ArrayList<>();
while ((line = br.readLine()) != null) {
list.add(Arrays.asList(line.split(",")));
}
// list即为所得,用于业务操作、数据持久保存等
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
if (br != null) {
br.close();
}
if (isr != null) {
isr.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 导出csv文件
* @param request
* @param response
* @throws IOException
*/
@RequestMapping(value = "/downloadFile", method = RequestMethod.POST)
public void downloadFile(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("application/x-download");
response.addHeader("Content-Disposition", "attachment;filename="+new String( "导出文件名".getBytes("utf-8"), "ISO8859-1" )+".csv");
OutputStream out = response.getOutputStream();
// 模拟生成字符串,一般是后台查询sql结果集拼接而成
String csvFile = ""客户姓名","客户类型","联系方式"n"张三","对私","13055874405t"n"XX集团","对公","0591-8857448t"";
// 向out中写入流
out.write((csvFile).toString().getBytes("gb2312"));
out.flush();
response.flushBuffer();
}
}
备注:生成csv文件若要为文本格式需在每个数据后面加t转义符;
出入参的编码根据实际情况转换(用GB2312编码或可避免中文缺失或乱码问题);
最后
以上就是精明钻石为你收集整理的java生成读取csv_Java Web读取/输出csv文件的全部内容,希望文章能够帮你解决java生成读取csv_Java Web读取/输出csv文件所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复