pom.xml
<!--POI Start-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-excelant</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.xmlbeans</groupId>
<artifactId>xmlbeans</artifactId>
<version>2.6.0</version>
</dependency>
<dependency>
<groupId>com.github.virtuald</groupId>
<artifactId>curvesapi</artifactId>
<version>1.04</version>
</dependency>
<!--POI End-->
ExcelUtils.java
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
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 java.io.*;
import java.util.Iterator;
/**
* Excel工具类
* @author jiabochao@live.com
* @version 2018-8-9 20:26:30
*/
public class ExcelUtils {
/**
* 将Excel文件转成字符串数组。支持xls、xlsx
* @param in Excel文件输入流
* @throws IOException
* @throws InvalidFormatException
*/
public static String[][] copyData(InputStream in) throws IOException, InvalidFormatException {
Workbook wb = WorkbookFactory.create(in);
Sheet sheet = wb.getSheetAt(0);
int rowNumber = sheet.getPhysicalNumberOfRows() - 1;
Iterator<Row> rowIterator = sheet.rowIterator();
Row titleRow = rowIterator.next();
int columnNumber = titleRow.getLastCellNum();
String[][] table = new String[rowNumber][columnNumber];
for (int i = 0; i < rowNumber && rowIterator.hasNext(); i++) {
Row row = rowIterator.next();
for (int j = 0; j < columnNumber; j++) {
Cell cell = row.getCell(j);
if (cell != null) {
cell.setCellType(CellType.STRING);
table[i][j] = cell.getStringCellValue().trim();
} else {
table[i][j] = "";
}
}
}
return table;
}
/**
* 将Excel文件转成字符串数组。支持xls、xlsx
* @param bytes Excel文件字节数组
* @throws IOException
* @throws InvalidFormatException
*/
public static String[][] copyData(byte[] bytes) throws IOException, InvalidFormatException {
return copyData(new ByteArrayInputStream(bytes));
}
/**
* 将Excel文件转成字符串数组。支持xls、xlsx
* @param file Excel文件
* @throws IOException
* @throws InvalidFormatException
*/
public static String[][] copyData(File file) throws IOException, InvalidFormatException {
return copyData(new FileInputStream(file));
}
}