前言:示例只是做了一個最最基礎的上傳csv的示例,如果要引用到代碼中去,還需要根據自己的業務自行添加一些邏輯處理。
readcsvutil工具類
package com.hanfengyeqiao.gjb.utils;
import java.io.*;
import java.util.*;
/**
* csv工具類
*/
public class readcsvutil {
private static final string fix="\ufeff";
/**
* 獲取csv文件內容
* @return 對象list
*/
public static list> getresource(byte[] bate) throws ioexception {
list> allstring = new arraylist();
map callloginfo ;
list list = new arraylist();
// 獲取文件內容
list = getsource(bate);
// 獲取文件表頭
list title = arrays.aslist(list.get(0).split(","));
string customername = title.get(0).trim();
string customerno = title.get(1).trim();
// 頭部會帶有"\ufeff"值
if(customername.startswith(fix)){
customername = customername.replace(fix, "");
}
callloginfo = new hashmap();
callloginfo.put("param1",customername);
callloginfo.put("param2",customerno);
allstring.add(callloginfo);
list.remove(0);
// 循環內容
for(int i = 0; i
list content = arrays.aslist(list.get(i).split(","));
// 當沒有添加額外參數時
if(content!=null){
callloginfo = new hashmap();
callloginfo.put("param1",content.get(0));
callloginfo.put("param2",content.get(1));
allstring.add(callloginfo);
}
}
return allstring;
}
/**
* 讀文件數據
*/
public static list getsource(byte[] bate) throws ioexception {
bufferedreader br = null;
bytearrayinputstream fis=null;
inputstreamreader isr = null;
try {
fis = new bytearrayinputstream(bate);
//指定以utf-8編碼讀入
isr = new inputstreamreader(fis,"utf-8");
br = new bufferedreader(isr);
} catch (exception e) {
e.printstacktrace();
}
string line;
string everyline ;
list allstring = new arraylist<>();
try {
//讀取到的內容給line變量
while ((line = br.readline()) != null){
everyline = line;
allstring.add(everyline);
}
} catch (ioexception e) {
e.printstacktrace();
}finally {
if(fis != null){
fis.close();
}
if(isr != null){
isr.close();
}
}
return allstring;
}
}
控制器(這里用的springboot):
package com.hanfengyeqiao.gjb.controller.admin;
import com.hanfengyeqiao.gjb.utils.readcsvutil;
import io.swagger.annotations.api;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.restcontroller;
import org.springframework.web.multipart.multipartfile;
import javax.servlet.http.httpservletrequest;
import java.util.list;
import java.util.map;
@api(tags = "")
@restcontroller
@requestmapping("/admin")
public class admincertcontroller {
@requestmapping("/test/upload")
public void upload(httpservletrequest request, multipartfile upfile) throws exception {
if (request.getmethod().equals("post")) {
byte[] bate =upfile.getbytes();
list> list=readcsvutil.getresource(bate);
if(list!=null){
for(map m:list){
system.out.println("param1:"+m.get("param1")+";param2:"+m.get("param2")+"。");
}
}
}
}
}
html代碼:
test上傳:
示例文件
運行結果
在處理csv文件的時候容易出現編碼上的問題,小伙伴們寫代碼的時候要多注意一下!
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持萬仟網。
如您對本文有疑問或者有任何想說的,請點擊進行留言回復,萬千網友為您解惑!