java后台读取csv文件工具类
public class CsvUtil {
private final static String CSV_LOWER = “csv”;
private final static String CSV = “CSV”;
private BufferedReader br = null;
private List list = new ArrayList();
public CsvUtil() {
}
public CsvUtil(MultipartFile file) throws Exception {
checkFile(file);
if (!file.isEmpty()) {
BufferedReader br = null;
InputStreamReader isr = null;
try {
isr = new InputStreamReader(file.getInputStream(),"GBK");
br = new BufferedReader(isr);
String stemp;
while ((stemp = br.readLine()) != null) {
list.add(stemp);
}
} catch (IOException e) {
log.error("error:{}", e);
} finally {
if (br != null) {
br.close();
}
if (isr != null) {
try {
isr.close();
} catch (IOException e) {
log.error("error:{}", e);
}
}
}
}
}
/**
* 检查文件格式
* @param file
* @throws IOException
*/
public static void checkFile(MultipartFile file) throws IOException {
// 判断文件是否存在
if (null == file) {
throw new FileNotFoundException("文件不存在");
}
// 获得文件名
String fileName = file.getOriginalFilename();
// 判断文件是否是excel文件
if (!fileName.endsWith(CSV_LOWER) && !fileName.endsWith(CSV)) {
throw new IOException(fileName + "不是csv文件");
}
}
public List getList() {
return list;
}
/**
* 获取行数
* @return
*/
public int getRowNum() {
return list.size();
}
/**
* 获取列数
* @return
*/
public int getColNum() {
if (!"[]".equals(list.toString())) {
// csv为逗号分隔文件
if (list.get(0).toString().contains(",")) {
return list.get(0).toString().split(",").length;
} else if (list.get(0).toString().trim().length() != 0) {
return 1;
} else {
return 0;
}
} else {
return 0;
}
}
/**
* 获取制定行
* @param index
* @return
*/
public String getRow(int index) {
if (this.list.size() != 0) {
return (String) list.get(index);
} else {
return null;
}
}
/**
* 获取指定列
* @param index
* @return
*/
public String getCol(int index) {
if (this.getColNum() == 0) {
return null;
}
StringBuffer sb = new StringBuffer();
String tmp = null;
int colnum = this.getColNum();
if (colnum > 1) {
for (Iterator it = list.iterator(); it.hasNext();) {
tmp = it.next().toString();
sb = sb.append(tmp.split(",")[index] + ",");
}
} else {
for (Iterator it = list.iterator(); it.hasNext();) {
tmp = it.next().toString();
sb = sb.append(tmp + ",");
}
}
String str = new String(sb.toString());
str = str.substring(0, str.length() - 1);
return str;
}
/**
* 获取某个单元格
* @param row
* @param col
* @return
*/
public String getString(int row, int col) {
String temp = null;
int colnum = this.getColNum();
if (colnum > 1) {
temp = list.get(row).toString().split(",",-1)[col];
} else if(colnum == 1){
temp = list.get(row).toString();
} else {
temp = null;
}
return temp;
}
public void csvClose()throws Exception{
this.br.close();
}
}