package com.controls.util;
import com.common.util.POIUtil;
import com.csvreader.CsvReader;
import com.performance.service.impl.ResumeManageService;
import jxl.read.biff.BiffException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
@Component
public class InputFile {
@Autowired
POIUtil pOIUtil;
@Value("${nas.file.path}")
private String nasPath;
private final static Logger logger = LoggerFactory.getLogger(ResumeManageService.class);
public List<List<String>> inputCSVorEXCEL(MultipartFile multipartFile)throws IOException, BiffException, ParseException {
List<List<String>> list=new ArrayList<List<String>>();
try{
String originalFilename=multipartFile.getOriginalFilename();
String uploadFileSuffix = originalFilename.substring(
originalFilename.lastIndexOf('.'));
if(uploadFileSuffix.equals(".csv")){
CsvReader csvReader = new CsvReader(multipartFile.getInputStream(), ',', Charset.forName("GBK"));
csvReader.readHeaders();
String[] headers = csvReader.getHeaders(); // 获取第一行表头
int headerCount = csvReader.getHeaderCount(); // 获取每行列数
list.add(Arrays.asList(headers));
while (csvReader.readRecord()) {
List<String> item=new ArrayList<>();
for(int i=0;i<headerCount;i++){
item.add(csvReader.get(i));
}
list.add(item);
}
}else {
Workbook workBook = null;
Sheet sheets;
FileInputStream fis = (FileInputStream) multipartFile.getInputStream();
if(originalFilename.endsWith(".xls")){
workBook=new HSSFWorkbook(fis);
}
if(originalFilename.endsWith(".xlsx")){
workBook=new XSSFWorkbook(fis);
}
sheets = workBook.getSheetAt(0);
fis.close();
Iterator<Row> rows = sheets.rowIterator();
Row row;
Cell cell;
while (rows.hasNext()) {
List<String> tem = new ArrayList<String>();
row = rows.next();
// 获取单元格
short cells = row.getLastCellNum();
for(int i=0;i<cells;i++){
cell = row.getCell(i);
String cellValue;
try {
cellValue = pOIUtil.getCellValue(cell).toString();
}catch (Exception e){
cellValue="";
}
tem.add(cellValue);
}
list.add(tem);
}
}
}catch (Exception e){
logger.warn(e.getMessage());
}
return list;
}
}
java导入.csv和excel文件并获取内容
最新推荐文章于 2024-04-26 12:04:39 发布