自己用的,如果读取大数据的excel,会很慢,我一般一次读取5w条数据
/**
* 读取.xls或者.xlsx结尾的Excel文件
* <p>fileName:Excel文件名
* <p>startRow:默认为0。从第几行开始读取
* <p>idxs:Excel列数组。idxs.length大于0时,读取数组中对应列的值,等于0或者null时,则读取所有列的值
* @author yangli : 2015-3-17
*/
public static String[][][] excelReader(String fileName, int startRow, InputStream is, int... idxs) throws Exception {
String[][][] str = null;
try {
if (startRow < 0) {
startRow = 0;
}
int len = 0;
if (null != idxs) {
len = idxs.length;
}
Workbook wook = null;
if (fileName.endsWith(".xls")) {
wook = new HSSFWorkbook(is);
} else if (fileName.endsWith(".xlsx")) {
wook = new XSSFWorkbook(is);
} else {
throw new Exception("请选择以.xls或者.xlsx结尾的Excel文件");
}
int nos = wook.getNumberOfSheets(); // 工作区间的个数
str = new String[nos][][];
for (int i = 0; i < nos; i++) {
Sheet sheet = wook.getSheetAt(i);// 获得一个sheet
if (null == sheet) {
continue;
}
int nor = sheet.getPhysicalNumberOfRows(); // 行数
if (nor == 0) {
continue;
}
int rnor = nor - startRow; // 要读取的行数
str[i] = new String[rnor][];
for (int r = startRow; r < nor; r++) {
Row row = sheet.getRow(r); // 获得一行
if (null == row) {
continue;
}
int noc = row.getPhysicalNumberOfCells(); // 每行中单元格数量
if (len > 0) {
str[i][r - startRow] = new String[len];
} else {
str[i][r - startRow] = new String[noc];
}
for (int c = row.getFirstCellNum(); c < noc; c++) {
if (len > 0) {
for (int idx = 0; idx < len; idx++) {
Cell cell = row.getCell(idxs[idx]);// 获得CELL值
if (null == cell) {
continue;
}
str[i][r - startRow][idx] = getCellValue(cell);
}
break;
} else {
Cell cell = row.getCell(c);
if (null == cell) {
continue;
}
str[i][r - startRow][c] = getCellValue(cell);
}
}
}
}
} catch (Exception e) {
throw e;
}
return str;
}
/**
* 读取cell内容
* @author yangli : 2015-3-17
*/
public static String getCellValue(Cell cell) {
String str = "";
switch (cell.getCellType()) {
case Cell.CELL_TYPE_BLANK:
str = "";
break;
case Cell.CELL_TYPE_BOOLEAN:
str = Boolean.toString(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
str = String.valueOf(cell.getDateCellValue());
} else {
cell.setCellType(Cell.CELL_TYPE_STRING);
String temp = cell.getStringCellValue();
// 判断是否包含小数点,如果不含小数点,则以字符串读取,如果含小数点,则转换为Double类型的字符串
if (temp.indexOf(".") > -1) { // >= 0
str = String.valueOf(new Double(temp)).trim();
} else {
str = temp.trim();
}
}
break;
case Cell.CELL_TYPE_STRING:
str = cell.getStringCellValue().trim();
break;
case Cell.CELL_TYPE_ERROR:
str = "";
break;
case Cell.CELL_TYPE_FORMULA:
cell.setCellType(Cell.CELL_TYPE_STRING);
str = cell.getStringCellValue();
if (null != str) {
str = str.replaceAll("#N/A", "").trim();
}
break;
default:
str = "";
break;
}
return str;
}