javapoi导入excel工具类
时间: 2023-09-12 07:10:57 浏览: 109
下面是使用Apache POI导入Excel的Java工具类示例:
```java
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
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;
public class ExcelUtils {
/**
* 读取Excel文件,返回一个二维数组
*
* @param filePath Excel文件路径
* @param sheetName 工作表名称
* @return 二维数组
* @throws IOException
*/
public static String[][] readExcel(String filePath, String sheetName) throws IOException {
Workbook workbook = null;
InputStream inputStream = new FileInputStream(filePath);
if (filePath.endsWith(".xls")) {
workbook = new HSSFWorkbook(inputStream);
} else if (filePath.endsWith(".xlsx")) {
workbook = new XSSFWorkbook(inputStream);
} else {
throw new RuntimeException("不支持的文件格式");
}
Sheet sheet = workbook.getSheet(sheetName);
int rowCount = sheet.getPhysicalNumberOfRows();
int columnCount = sheet.getRow(0).getPhysicalNumberOfCells();
String[][] data = new String[rowCount - 1][columnCount];
for (int i = 1; i < rowCount; i++) {
Row row = sheet.getRow(i);
for (int j = 0; j < columnCount; j++) {
Cell cell = row.getCell(j);
data[i - 1][j] = cell.toString();
}
}
workbook.close();
inputStream.close();
return data;
}
}
```
使用示例:
```java
String filePath = "path/to/excel/file.xlsx";
String sheetName = "Sheet1";
String[][] data = ExcelUtils.readExcel(filePath, sheetName);
```
阅读全文