读取excle数据
依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.1</version>
</dependency>
<dependency>
<groupId>org.apache.xmlbeans</groupId>
<artifactId>xmlbeans</artifactId>
<version>3.0.2</version>
</dependency>
工具类
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
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.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/**
* @author wyc
* @date 2019/8/7 15:28
*/
public class ReadExcelUtil {
private static final Logger logger = Logger.getLogger(ExportUtil.class);
private static final String EXCEL_XLS = ".xls";
private static final String EXCEL_XLSX = ".xlsx";
/**
*读取excel数据
* @throws Exception
*
*/
public static List<List<String>> readExcelInfo(String url) throws Exception{
/*
* workbook:工作簿,就是整个Excel文档
* sheet:工作表
* row:行
* cell:单元格
*/
// BufferedWriter bw = new BufferedWriter(new FileWriter(new File(url)));
// 支持excel2003、2007
File excelFile = new File(url);//创建excel文件对象
InputStream is = new FileInputStream(excelFile);//创建输入流对象
checkExcelVaild(excelFile);
// Workbook workbook = getWorkBook(is, excelFile); //有点问题
Workbook workbook = WorkbookFactory.create(is);//同时支持2003、2007、2010
// 获取Sheet数量
int sheetNum = workbook.getNumberOfSheets();
// 创建二维数组保存所有读取到的行列数据,外层存行数据,内层存单元格数据
List<List<String>> dataList = new ArrayList<List<String>>();
// FormulaEvaluator formulaEvaluator = null;
// 遍历工作簿中的sheet,第一层循环所有sheet表
for(int index = 0;index<sheetNum;index++){
Sheet sheet = workbook.getSheetAt(index);
if(sheet==null){
continue;
}
System.out.println("表单行数:"+sheet.getLastRowNum());
// 如果当前行没有数据跳出循环,第二层循环单sheet表中所有行
for(int rowIndex=0;rowIndex<=sheet.getLastRowNum();rowIndex++){
Row row = sheet.getRow(rowIndex);
// 根据文件头可以控制从哪一行读取,在下面if中进行控制
if(row==null){
continue;
}
// 遍历每一行的每一列,第三层循环行中所有单元格
List<String> cellList = new ArrayList<String>();
for(int cellIndex=0;cellIndex<row.getLastCellNum();cellIndex++){
Cell cell = row.getCell(cellIndex);
cellList.add(getCellValue(cell));
}
dataList.add(cellList);
}
}
is.close();
return dataList;
}
/**
*获取单元格的数据,暂时不支持公式
*
*
*/
public static String getCellValue(Cell cell){
CellType cellType = cell.getCellTypeEnum();
String cellValue = "";
if(cell==null || cell.toString().trim().equals("")){
return null;
}
if(cellType==CellType.STRING){
cellValue = cell.getStringCellValue().trim();
return cellValue = isBlank(cellValue) ? "" : cellValue;
}
if(cellType==CellType.NUMERIC){
if (HSSFDateUtil.isCellDateFormatted(cell)) { //判断日期类型
cellValue = DateToString(cell.getDateCellValue());
} else { //否
cellValue = new DecimalFormat("#.######").format(cell.getNumericCellValue());
}
return cellValue;
}
if(cellType==CellType.BOOLEAN){
cellValue = String.valueOf(cell.getBooleanCellValue());
return cellValue;
}
return null;
}
/**
*判断excel的版本,并根据文件流数据获取workbook
* @throws IOException
*
*/
public static Workbook getWorkBook(InputStream is,File file) throws Exception{
Workbook workbook = null;
if(file.getName().endsWith(EXCEL_XLS)){
workbook = new HSSFWorkbook(is);
}else if(file.getName().endsWith(EXCEL_XLSX)){
workbook = new XSSFWorkbook(is);
}
return workbook;
}
/**
*校验文件是否为excel
* @throws Exception
*/
public static void checkExcelVaild(File file) throws Exception {
String message = "该文件是EXCEL文件!";
if(!file.exists()){
message = "文件不存在!";
throw new Exception(message);
}
if(!file.isFile()||((!file.getName().endsWith(EXCEL_XLS)&&!file.getName().endsWith(EXCEL_XLSX)))){
System.out.println(file.isFile()+"==="+file.getName().endsWith(EXCEL_XLS)+"==="+file.getName().endsWith(EXCEL_XLSX));
System.out.println(file.getName());
message = "文件不是Excel";
throw new Exception(message);
}
}
/**
* 将date类型转换为String类型
* @param date
*/
private static String DateToString(Date date) {
if (date == null) {
date = new Date();
}
DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return format1.format(date);
}
/**
* 判断字符串是否为空
* @return true:空,false:非空
*/
private static boolean isBlank(String s){
if(s == null){
return true;
}
if("".equals(s)){
return true;
}
if("".equals(s.trim())){
return true;
}
return false;
}
}
main方法测试
public static void main(String[] args) throws Exception {
//外层集合装的是每一行的数据,内层集合装的是每一行中每列的数据
List<List<String>> list = readExcelInfo("D:\\aaa.xlsx");
for (List<String> stringList : list) {
System.out.println(stringList);
//......处理数据
}
}
读取CSV数据
依赖
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>lang3</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>com.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>4.4</version>
</dependency>
工具类
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* @author wyc
* @date 2019/8/7 16:26
*/
public class ReadCsvUtil {
public static List<List<String>> readCsv() {
List<List<String>> records = new ArrayList<>();
String record;
// 设定UTF-8字符集,使用带缓冲区的字符输入流BufferedReader读取文件内容
BufferedReader file = null;
try {
file = new BufferedReader(new InputStreamReader(new FileInputStream("D:\\bbb.csv"), "GBK"));
file.readLine(); //跳过表头所在的行
// 遍历数据行并存储在名为records的ArrayList中
while ((record = file.readLine()) != null) {
String fields[] = record.split(",");
List<String> list = Arrays.asList(fields);
records.add(list);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if (file!= null){
try {
// 关闭文件
file.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return records;
}
}
main方法测试
public static void main(String[] args) {
List<List<String>> lists = readCsv();
System.out.println(lists);
for (List<String> list : lists) {
System.out.println(list);
//.......处理数据
}
}