当大家进行这一操作的时候通常会遇到如下问题。
1: 想分割数据 例如:
"123","Jack jona","Computer science"
"234","Joen Dan", "Philosophy"
//当遇到这种数据的时候可直接用 逗号进行分割。
2: 分割数据如下:
"123", "jack jona", "New York, NY"
"234", "Lee Jack", "Fort myers, FL"
//当遇到这种数据的时候可以直接使用
,(?=([^"]*"[^"]*")*[^"]*$)
3.匹配是否是整数:
Pattern pattern = Pattern.compile("^[-\+]?[\d]*$");
pattern.matcher(str).matches()
4.下载csv模板:
public void downCsvModel(HttpServletRequest request, HttpServletResponse resp) {
try {
resp.setHeader("Content-Disposition","attachment; filename=anti.csv");
OutputStreamWriter osw = new OutputStreamWriter(resp.getOutputStream(), "GBK");
String head = "字段一,字段二,字段三,";
osw.write(new String(new byte[] { (byte) 0xEF, (byte) 0xBB,(byte) 0xBF }));//设置头部属性
osw.write(head);
osw.flush();
osw.close();
} catch (Exception e) {
logger.error(e.getLocalizedMessage());
}
}
5.文件流导入csv模板
Controller:
@PostMapping("uploadcsv")
@ResponseBody
public void uploadCsv(@RequestBody MultipartFile file) {//方法返回值根据实际情况而定
try {
service.uploadInfoCsv(file.getInputStream());//service已预先加载实例
} catch (IOException e) {
e.getMessage();
}
}
Service:
public void uploadInfoCsv(InputStream inputStream) {
try {
BufferedReader br = new BufferedReader(
new InputStreamReader(inputStream),"GBK");//编码格式
boolean f = false;//跳过第一行
String str = null;
while ((str = br.readLine()) != null){
if (!f) {
f = true;
continue;
}
rowOption(str,entitys,result,msg);//行操作
}
br.close();
inputStream.close();
} catch (Exception e) {
logger.error(e.getLocalizedMessage());
return Result.newError();
}
}
6. split 逗号分隔,保留空值
最后的几个空值希望按空值来存
这时只使用split(",")会产生问题。
可改为split(",",-1)