1、添加依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.13</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>3.13</version>
</dependency>
2、支持只读一个sheet的工具类
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
/**
* POI解析Excel---只读一个sheet
* 注意:1、若单元格为空时,读出为""空字符串;列数为按最后一列计算;
* 2、如果在最后一列前单元格合并数据个数还是按合并前列数算,但是合并后单元格只有左上单元格有数据;
* 3、如果是最后一列合并单元格,则算最前面一列 ,后面列不计算 在其中,也没数据(不是""空串)
*/
public class ExcelReader {
/**
* 根据fileType不同读取excel文件
*
* @param path
* @param path
* @throws IOException
*/
public static List<List<String>> readExcel(String path) {
String fileType = path.substring(path.lastIndexOf(".") + 1);
// return a list contains many list
List<List<String>> lists = new ArrayList<List<String>>();
//读取excel文件
InputStream is = null;
try {
is = new FileInputStream(path);
//获取工作薄
Workbook wb = null;
if (fileType.equals("xls")) {
wb = new HSSFWorkbook(is);
} else if (fileType.equals("xlsx")) {
wb = new XSSFWorkbook(is);
} else {
return null;
}
//读取第一个工作页sheet
Sheet sheet = wb.getSheetAt(0);
//第一行为标题
for (Row row : sheet) {
ArrayList<String> list = new ArrayList<String>();
int flag = 0;
System.out.println(">>>>>>>>>>>"+row.getLastCellNum());
for (int i = 0; i < row.getLastCellNum(); i++) {
Cell cell = row.getCell(i);
//根据不同类型转化成字符串
//如果单元格是空(列)的跳过-----------合并的单元格值优先属于左上单元格
if(cell == null){
list.add("");
}else if(cell.getCellType() ==3){
list.add("");
}else if(cell.getCellType() ==0){
list.add(handleNumber(String.valueOf(cell.getNumericCellValue())));
flag = 1;
}else if(cell.getCellType() ==1){
cell.setCellType(Cell.CELL_TYPE_STRING);
list.add(cell.getStringCellValue());
flag = 1;
}else {
list.add("");
}
}
//如果整行都没有值,跳过整行
if(list.size() != 0 && flag == 1){
lists.add(list);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (is != null) is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return lists;
}
/**
* <b> 去掉数字字符串小数点后面无效的领,或者去掉小数点
* </b><br><br><i>Description</i> :
* @param number String
* @return java.lang.String
* <br><br>Date: 2019/11/14 11:17 <br>Author : dxl
*/
public static String handleNumber(String number){
if(number.contains(".") && number.substring(number.indexOf(".")+1,number.length()).length() == 16){
if(number.substring(number.length()-1,number.length()).equals("1")){
number = number.substring(0,number.length()-1);
}else if(number.substring(number.length()-1,number.length()).equals("9")){
Double tem = Double.valueOf(number) + 0.0000000000000002;
number = tem.toString();
}
}
if(!number.contains(".")){
return number;
}else if(number.lastIndexOf(".") == number.length()-1){
number = number.substring(0,number.length()-1);
return number;
}else if(number.substring(number.length()-1,number.length()).equals("0")){
number = number.substring(0,number.length()-1);
number = handleNumber(number);
}else {
return number;
}
return number;
}
/**
* 创建Excel.xls
* @param lists 需要写入xls的数据
* @param titles 列标题
* @param name 文件名
* @return
* @throws IOException
*/
public static Workbook creatExcel(List<List<String>> lists, String[] titles, String name) throws IOException {
System.out.println(lists);
//创建新的工作薄
Workbook wb = new HSSFWorkbook();
// 创建第一个sheet(页),并命名
Sheet sheet = wb.createSheet(name);
// 手动设置列宽。第一个参数表示要为第几列设;,第二个参数表示列的宽度,n为列高的像素数。
for(int i=0;i<titles.length;i++){
sheet.setColumnWidth((short) i, (short) (35.7 * 150));
}
// 创建第一行
Row row = sheet.createRow((short) 0);
// 创建两种单元格格式
CellStyle cs = wb.createCellStyle();
CellStyle cs2 = wb.createCellStyle();
// 创建两种字体
Font f = wb.createFont();
Font f2 = wb.createFont();
// 创建第一种字体样式(用于列名)
f.setFontHeightInPoints((short) 10);
f.setColor(IndexedColors.BLACK.getIndex());
f.setBoldweight(Font.BOLDWEIGHT_BOLD);
// 创建第二种字体样式(用于值)
f2.setFontHeightInPoints((short) 10);
f2.setColor(IndexedColors.BLACK.getIndex());
// 设置第一种单元格的样式(用于列名)
cs.setFont(f);
cs.setBorderLeft(CellStyle.BORDER_THIN);
cs.setBorderRight(CellStyle.BORDER_THIN);
cs.setBorderTop(CellStyle.BORDER_THIN);
cs.setBorderBottom(CellStyle.BORDER_THIN);
cs.setAlignment(CellStyle.ALIGN_CENTER);
// 设置第二种单元格的样式(用于值)
cs2.setFont(f2);
cs2.setBorderLeft(CellStyle.BORDER_THIN);
cs2.setBorderRight(CellStyle.BORDER_THIN);
cs2.setBorderTop(CellStyle.BORDER_THIN);
cs2.setBorderBottom(CellStyle.BORDER_THIN);
cs2.setAlignment(CellStyle.ALIGN_CENTER);
//设置列名
for(int i=0;i<titles.length;i++){
Cell cell = row.createCell(i);
cell.setCellValue(titles[i]);
cell.setCellStyle(cs);
}
if(lists == null || lists.size() == 0){
return wb;
}
//设置每行每列的值
for (short i = 1; i <= lists.size(); i++) {
// Row 行,Cell 方格 , Row 和 Cell 都是从0开始计数的
// 创建一行,在页sheet上
Row row1 = sheet.createRow((short)i);
for(short j=0;j<titles.length;j++){
// 在row行上创建一个方格
Cell cell = row1.createCell(j);
cell.setCellValue(lists.get(i-1).get(j));
cell.setCellStyle(cs2);
}
}
return wb;
}
public static void main(String[] args) {
double ii = (double)10/(double)3;
System.out.println(">>>>ii>>>>"+ii);
String path = "D:/111.xls";
List<List<String>> lists = readExcel(path);
for (List<String> list : lists) {
System.out.println(">>"+list);
System.out.println("--------------------------");
for (String strs : list) {
System.out.println(strs);
}
}
}
}
3、支持多个sheet数据读取工具类
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.*;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
* 读取Excel数据工具类----可以读取多个sheet
* 注意:1、若单元格为空时,读出为""空字符串;列数为按最后一列计算;
* 2、如果在最后一列前单元格合并数据个数还是按合并前列数算,但是合并后单元格只有左上单元格有数据;
* 3、如果是最后一列合并单元格,则算最前面一列 ,后面列不计算 在其中,也没数据(不是""空串)
* @time 2017-06-03
*/
public class ExcelReaderPlus {
private static HSSFWorkbook wb;
private static HSSFSheet sheet;
private static HSSFRow row;
private static XSSFWorkbook wbx;
private static XSSFSheet sheetx;
private static XSSFRow rowx;
/**
* 获取多个sheetExcel表格数据
* 注意:1、若单元格为空时,读出为""空字符串;列数为按最后一列计算;
* 2、如果在最后一列前单元格合并还是数据个数还是按合并前列数算,但是合并后单元格只有左上单元格有数据;
* 3、如果是最后一列合并单元格,则算最前面一列 ,后面列不计算 在其中,也没数据(不是""空串)
* @param filePath Excel路径
* @return
*/
public ExcelData readExcel(String filePath) {
InputStream is = null;
File file = new File(filePath);
try {
is = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
ExcelData excelData = new ExcelData();
try {
if(filePath.substring(filePath.length()-5,filePath.length()).equals(".xlsx")){
wbx = new XSSFWorkbook(is);
return readExcelx(wbx,file.getName());
}
wb = new HSSFWorkbook(is);
} catch (IOException e) {
e.printStackTrace();
}
Integer sheetNum = wb.getNumberOfSheets();
excelData.setSheetSum(sheetNum);
excelData.setFileName(file.getName());
//循环获取所有sheet数据
List<ExcelSheetData> sheetDatas = new ArrayList<>();
for (int i = 0; i < sheetNum; i++) {
ExcelSheetData sheetData = new ExcelSheetData();
sheet = wb.getSheetAt(i);
sheetData.setLineSum(sheet.getPhysicalNumberOfRows());
sheetData.setSheetName(sheet.getSheetName());
List<ExcelLineData> lineDatas = readExcelContentBySheet(sheet);
sheetData.setLineData(lineDatas);
sheetDatas.add(sheetData);
}
excelData.setSheetData(sheetDatas);
return excelData;
}
private ExcelData readExcelx(XSSFWorkbook wbx,String fileName) {
ExcelData excelData = new ExcelData();
Integer sheetNum = wbx.getNumberOfSheets();
excelData.setSheetSum(sheetNum);
excelData.setFileName(fileName);
//循环获取所有sheet数据
List<ExcelSheetData> sheetDatas = new ArrayList<>();
for (int i = 0; i < sheetNum; i++) {
ExcelSheetData sheetData = new ExcelSheetData();
sheetx = wbx.getSheetAt(i);
sheetData.setSheetName(sheetx.getSheetName());
sheetData.setLineSum(sheetx.getPhysicalNumberOfRows());
List<ExcelLineData> lineDatas = readExcelContentBySheetx(sheetx);
sheetData.setLineData(lineDatas);
sheetDatas.add(sheetData);
}
excelData.setSheetData(sheetDatas);
return excelData;
}
private List<ExcelLineData> readExcelContentBySheet(HSSFSheet sheet) {
List<ExcelLineData> lineDatas = new ArrayList<>();
// 得到总行数
int rowNum = sheet.getLastRowNum();
for (int i = 0; i <= rowNum; i++) {
int j = 0;
row = sheet.getRow(i);
if (Objects.isNull(row)) {
continue;
}
int colNum = row.getLastCellNum();
ExcelLineData lineData = new ExcelLineData();
List<String> colData = new ArrayList<>();
lineData.setColSum(colNum);
while (j < colNum) {
String value = getCellValue(row.getCell(j)).trim();
colData.add(value);
j++;
}
lineData.setColData(colData);
lineDatas.add(lineData);
}
return lineDatas;
}
private List<ExcelLineData> readExcelContentBySheetx(XSSFSheet sheetx) {
List<ExcelLineData> lineDatas = new ArrayList<>();
// 得到总行数
int rowNum = sheetx.getLastRowNum();
for (int i = 0; i <= rowNum; i++) {
int j = 0;
rowx = sheetx.getRow(i);
if (Objects.isNull(rowx)) {
continue;
}
int colNum = rowx.getLastCellNum();
ExcelLineData lineData = new ExcelLineData();
List<String> colData = new ArrayList<>();
lineData.setColSum(colNum);
while (j < colNum) {
String value = getCellValuex(rowx.getCell(j)).trim();
colData.add(value);
j++;
}
lineData.setColData(colData);
lineDatas.add(lineData);
}
return lineDatas;
}
/**
* 获取单元格数据
*
* @param cell Excel单元格
* @return String 单元格数据内容
*/
private String getCellValue(HSSFCell cell) {
if (Objects.isNull(cell)) {
return "";
}
String value = "";
switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_NUMERIC: // 数字
//如果为时间格式的内容
if (HSSFDateUtil.isCellDateFormatted(cell)) {
//注:format格式 yyyy-MM-dd hh:mm:ss 中小时为12小时制,若要24小时制,则把小h变为H即可,yyyy-MM-dd HH:mm:ss
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
value = sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue())).toString();
break;
} else {
value = new DecimalFormat("0").format(cell.getNumericCellValue());
}
break;
case HSSFCell.CELL_TYPE_STRING: // 字符串
value = cell.getStringCellValue();
break;
case HSSFCell.CELL_TYPE_BOOLEAN: // Boolean
value = cell.getBooleanCellValue() + "";
break;
case HSSFCell.CELL_TYPE_FORMULA: // 公式
value = cell.getCellFormula() + "";
break;
case HSSFCell.CELL_TYPE_BLANK: // 空值
value = "";
break;
case HSSFCell.CELL_TYPE_ERROR: // 故障
value = "非法字符";
break;
default:
value = "未知类型";
break;
}
return value;
}
private String getCellValuex(XSSFCell cellx) {
if (Objects.isNull(cellx)) {
return "";
}
String value = "";
switch (cellx.getCellType()) {
case XSSFCell.CELL_TYPE_NUMERIC: // 数字
//如果为时间格式的内容
if (HSSFDateUtil.isCellDateFormatted(cellx)) {
//注:format格式 yyyy-MM-dd hh:mm:ss 中小时为12小时制,若要24小时制,则把小h变为H即可,yyyy-MM-dd HH:mm:ss
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
value = sdf.format(HSSFDateUtil.getJavaDate(cellx.getNumericCellValue())).toString();
break;
} else {
value = new DecimalFormat("0").format(cellx.getNumericCellValue());
}
break;
case XSSFCell.CELL_TYPE_STRING: // 字符串
value = cellx.getStringCellValue();
break;
case XSSFCell.CELL_TYPE_BOOLEAN: // Boolean
value = cellx.getBooleanCellValue() + "";
break;
case XSSFCell.CELL_TYPE_FORMULA: // 公式
value = cellx.getCellFormula() + "";
break;
case XSSFCell.CELL_TYPE_BLANK: // 空值
value = "";
break;
case XSSFCell.CELL_TYPE_ERROR: // 故障
value = "非法字符";
break;
default:
value = "未知类型";
break;
}
return value;
}
public static void main(String[] args) {
ExcelReaderPlus excelReader = new ExcelReaderPlus();
ExcelData excelData = excelReader.readExcel("D:\\111.xls");
System.out.println(excelData.toString());
for(ExcelSheetData excelSheetData:excelData.getSheetData()){
System.out.println("**********************"+excelSheetData.getSheetName());
for(ExcelLineData excelLineData :excelSheetData.getLineData()){
System.out.println("----------------"+excelLineData.getColSum());
System.out.println(">>>>>>>"+excelLineData.getColData());
}
}
}
public class ExcelData {
private int sheetSum;
private String fileName;
private List<ExcelSheetData> sheetData;
public int getSheetSum() {
return sheetSum;
}
public void setSheetSum(int sheetSum) {
this.sheetSum = sheetSum;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public List<ExcelSheetData> getSheetData() {
return sheetData;
}
public void setSheetData(List<ExcelSheetData> sheetData) {
this.sheetData = sheetData;
}
}
public class ExcelSheetData {
/**
* 工作簿名称
*/
private String sheetName;
/**
* 表格总行数
*/
private int lineSum;
/**
* 行数据集合
*/
private List<ExcelLineData> lineData;
public String getSheetName() {
return sheetName;
}
public void setSheetName(String sheetName) {
this.sheetName = sheetName;
}
public int getLineSum() {
return lineSum;
}
public void setLineSum(int lineSum) {
this.lineSum = lineSum;
}
public List<ExcelLineData> getLineData() {
return lineData;
}
public void setLineData(List<ExcelLineData> lineData) {
this.lineData = lineData;
}
}
public class ExcelLineData {
/**
* 行编号
*/
private int lineNumber;
/**
* 行总列数
*/
private int colSum;
/**
* 列数据集合
*/
private List<String> colData;
public int getLineNumber() {
return lineNumber;
}
public void setLineNumber(int lineNumber) {
this.lineNumber = lineNumber;
}
public int getColSum() {
return colSum;
}
public void setColSum(int colSum) {
this.colSum = colSum;
}
public List<String> getColData() {
return colData;
}
public void setColData(List<String> colData) {
this.colData = colData;
}
}
}