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 java.io.FileInputStream;
import java.io.InputStream;
import java.util.*;
public class ReadExcel {
public static void main(String[] args) {
try {
List<Map<String, String>> maps = readExcel("e:/User/xxx/xx.xls");
for (Map<String,String> map : maps){
Set<Map.Entry<String,String>> es = map.entrySet();
for (Map.Entry<String, String> entry : es) {
System.out.println(entry.getValue()+"\t");
}
System.out.println();
}
} catch (Exception e) {
e.printStackTrace();
}
}
// 根据excel文件路径返回list list对应一张表的数据,list里面是多个map集合,一个map对应一行数据
public static List<Map<String,String>> readExcel(String fileName) throws Exception {
List<Map<String,String>> sheetList = new ArrayList<>();
FileInputStream fis = new FileInputStream(fileName);
Workbook workbook = null;
if(fileName.toLowerCase().endsWith("xlsx")){
workbook = new XSSFWorkbook(fis);
}else if (fileName.toLowerCase().endsWith("xls")){
workbook = new HSSFWorkbook(fis);
}
Sheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = sheet.iterator();
rowIterator.next();//跳过第一行
while (rowIterator.hasNext()){
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
Map<String,String> mapRow = new HashMap<String,String>();
while (cellIterator.hasNext()){
Cell cell = cellIterator.next();
int a = cell.getCellType();//获取列的类型
if(a==0){
double d = cell.getNumericCellValue();
mapRow.put(cell.getColumnIndex()+"",d+"");
}else if (a==1){
String v = cell.getStringCellValue();
mapRow.put(cell.getColumnIndex()+"",v);
}
}
sheetList.add(mapRow);
}
return sheetList;
}
public static List<Map<String,String>> readExcel1(InputStream inputStream, String fileName) throws Exception {
List<Map<String,String>> sheetList = new ArrayList<>();
InputStream fis = inputStream;
Workbook workbook = null;
if(fileName.toLowerCase().endsWith("xlsx")){
workbook = new XSSFWorkbook(fis);
}else if (fileName.toLowerCase().endsWith("xls")){
workbook = new HSSFWorkbook(fis);
}
Sheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = sheet.iterator();
rowIterator.next();//跳过第一行
while (rowIterator.hasNext()){
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
Map<String,String> mapRow = new HashMap<String,String>();
while (cellIterator.hasNext()){
Cell cell = cellIterator.next();
int a = cell.getCellType();//获取列的类型
if(a==0){
double d = cell.getNumericCellValue();
mapRow.put(cell.getColumnIndex()+"",d+"");
}else if (a==1){
String v = cell.getStringCellValue();
mapRow.put(cell.getColumnIndex()+"",v);
}
}
sheetList.add(mapRow);
}
return sheetList;
}
}
poi获取excel的数据
最新推荐文章于 2023-09-04 09:42:38 发布