讀取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);
//.......處理數據
}
}