public class ImportUtil {
private static final int version2003 = 2003;
private static final int version2007 = 2007;
private static int version = version2003;
private static Workbook wb = null;
private static Sheet sheet = null;
private static Cell cell = null;
private static org.apache.poi.ss.usermodel.Row row = null;
public static void main(String[] args) throws FileNotFoundException, IOException{
// ImportUtil i = new ImportUtil();
// String[][] data = i.getData("D:/workspace/jz.xlsx", 0);
// String[][] data = i.getData("D:/workspace/world.xls", 0);
//至于插数据库那就是你的事了
//循环取值data[0][0]就是第一列第一格的数据
}
/**
* * * 读取Excel的内容,第一维数组存储的是一行中格列的值,二维数组存储的是多少个行
*
* @param excelFilePath
* 读取数据的源Excel路径
* @return 读出的Excel中数据的内容
* @throws FileNotFoundException
* @throws IOException
*/
public static String[][] getData(String excelFilePath)
throws FileNotFoundException, IOException {
if (excelFilePath.endsWith(".xls"))
version = version2003;
else if (excelFilePath.endsWith(".xlsx"))
version = version2007;
InputStream stream = null;
if (version == version2003) {
stream = new FileInputStream(excelFilePath);
wb = (Workbook) new HSSFWorkbook(stream);
} else if (version == version2007) {
wb = (Workbook) new XSSFWorkbook(excelFilePath);
}
sheet = wb.getSheetAt(0);
// 行数(从0开始,相当于最后一行的索引),列数
int count_row = sheet.getLastRowNum(), count_cell = sheet.getRow(0).getPhysicalNumberOfCells();
String[][] returnArray = new String[count_row][count_cell];
for (int i = 0; i < count_row; i++) {
for (int j = 0; j < count_cell; j++) {
row = sheet.getRow(i + 1);
cell = ((org.apache.poi.ss.usermodel.Row) row).getCell(j);
if(cell == null){
returnArray[i][j] = "";
}else{
int type = cell.getCellType(); // 得到单元格数据类型
String k = "";
switch (type) { // 判断数据类型
case Cell.CELL_TYPE_BLANK:
k = "";
break;
case Cell.CELL_TYPE_BOOLEAN:
k = (cell.getBooleanCellValue() == true ? "Y"
: "N");
break;
case Cell.CELL_TYPE_ERROR:
k = cell.getErrorCellValue() + "";
break;
case Cell.CELL_TYPE_FORMULA:
if (!cell.getStringCellValue().equals("")) {
k = cell.getStringCellValue();
} else {
k = cell.getNumericCellValue() + "";
}
break;
case Cell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
Date date = cell.getDateCellValue();
if (date != null) {
k = new SimpleDateFormat("yyyy-MM-dd").format(date);
} else {
k = "";
}
} else {
k = new DecimalFormat("0").format(cell
.getNumericCellValue());
}
break;
case Cell.CELL_TYPE_STRING:
k = cell.getStringCellValue();
break;
default:
k = "";
break;
}
returnArray[i][j] = k;
}
}
}
return returnArray;
}
}