public static void main(String[] args) throws Exception {
String namePath="D://file//测试.xls";
//String namePath="D://file//测试.xlsx";
List<Map<String,String>> lists=loadExcel(namePath);
for(int i=0;i<lists.size();i++){
Map<String,String> map=lists.get(i);
}
}
public static List<Map<String,String>> loadExcel(String filepath) throws Exception{
List<Map<String,String>> datas = new ArrayList<Map<String,String>>();
//导入.xls与.xlsx判断
if(filepath.indexOf(".xlsx")>-1){//=======导入.xlsx文件
XSSFWorkbook xssfWorkbook = new XSSFWorkbook(new FileInputStream(filepath));
XSSFSheet sheet0= xssfWorkbook.getSheetAt(0);
int rows0=sheet0.getPhysicalNumberOfRows();
for(int i = 1; i < rows0; i++){
XSSFRow xssfRow = sheet0.getRow(i);
// 行不为空
if (xssfRow != null ) {
// 获取到Excel文件中的所有的列
int cells0 = xssfRow.getPhysicalNumberOfCells();
String value = "";
// 遍历列
for (int j = 0; j < cells0; j++) {
// 获取到列的值
XSSFCell cell = xssfRow.getCell(j);
if (cell != null) {
switch (cell.getCellType()) {
case XSSFCell.CELL_TYPE_FORMULA:
break;
case XSSFCell.CELL_TYPE_NUMERIC:
value += cell.getNumericCellValue() + ",";
break;
case XSSFCell.CELL_TYPE_STRING:
value += cell.getStringCellValue() + ",";
break;
default:
value += "0";
break;
}
}
}
// 将数据插入到mysql数据库中
String[] val = value.split(",");
if(!"".equals(val[0])&&val[0]!=null ){
Map map=new HashMap<String,String>();
for(int k=0;k<val.length;k++){
map.put(""+k, val[k]);
}
datas.add(map);
}
}
}
}else if(filepath.indexOf(".xls")>-1){ //=======导入.xls文件
// 创建对Excel工作簿文件的引用
HSSFWorkbook wookbook = new HSSFWorkbook(new FileInputStream(filepath));
// 在Excel文档中,第一张工作表的缺省索引是0
// 其语句为:HSSFSheet sheet = workbook.getSheetAt(0);
HSSFSheet sheet = wookbook.getSheetAt(0);
//HSSFSheet sheet = wookbook.getSheet("Sheet1");
// 获取到Excel文件中的所有行数
int rows = sheet.getPhysicalNumberOfRows();
for (int i = 1; i < rows; i++) {
// 读取左上端单元格
HSSFRow row = sheet.getRow(i);
// 行不为空
if (row != null ) {
// 获取到Excel文件中的所有的列
int cells = row.getPhysicalNumberOfCells();
String value = "";
// 遍历列
for (int j = 0; j < cells; j++) {
// 获取到列的值
HSSFCell cell = row.getCell(j);
if (cell != null) {
switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_FORMULA:
break;
case HSSFCell.CELL_TYPE_NUMERIC:
value += cell.getNumericCellValue() + ",";
break;
case HSSFCell.CELL_TYPE_STRING:
value += cell.getStringCellValue() + ",";
break;
default:
value += "0";
break;
}
}
}
// 将数据插入到mysql数据库中
String[] val = value.split(",");
if(!"".equals(val[0])&&val[0]!=null ){
Map map=new HashMap<String,String>();
for(int k=0;k<val.length;k++){
map.put(""+k, val[k]);
}
datas.add(map);
}
}
}
}
return datas;
}