才第二天就差点开始放弃治疗了…
下班了。补一个今天写到的东西。
相关jar包
maven项目的话是引 poi-ooxml 这个包
<!-- excel -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.0.1</version>
</dependency>
一般方法
可能用到的引用类
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.OfficeXmlFileException;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
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.xssf.usermodel.XSSFWorkbook;
获取相关对象
File file = new File("X:\\Y\\Excel");
Workbook wb = null;
FileInputStream fis = new FileInputStream(file);;
int end = file.getName().lastIndexOf(".");
//根据后缀名使用不同的方法解析
if (end != -1 && fList[i].getName().substring(end).equalsIgnoreCase(".xls")) {
wb = (Workbook) new HSSFWorkbook(new POIFSFileSystem(fis));
} else if (end != -1 && fList[i].getName().substring(end).equalsIgnoreCase(".xlsx")) {
wb = (Workbook) new XSSFWorkbook(fis);
}
//获取sheet个数
int num = wb.getNumberOfSheets();
for(int i = 0;i<num;i++) {
Sheet sheet = wb.getSheetAt(i);//准备处理sheet
Map<String, Integer> map = checktitle(sheet, EXCEL_TITLE);//这里使用一个自定义方法来获取表头在第几列
for (Row row : sheet) {
if (row.getCell(map.get("字段名称")) != null&& row.getCell(map.get("字段名称")).getCellType() == CellType.STRING) {
String valX= row.getCell(map.get("字段名称")).getStringCellValue();//获取到了值 不同数据类型换不同的东西接就可以了
}
}
}
fis.close();
private final static String[] EXCEL_TITLE = new String[] { "字段名1","字段名2"};
protected static Map<String, Integer> checktitle(Sheet sheet, String[] str) {
Map<String, Integer> map = new HashMap<String, Integer>();
if (sheet == null) {
return map;
}
Row firstRow = sheet.getRow(0);
int flag = 0;
if (firstRow != null) {
for (int j = 0; j < str.length; j++) {
/*********** 是循环不为空的列个数********************/
for (int i = 0; i < firstRow.getPhysicalNumberOfCells(); i++) {
if (firstRow.getCell(i) == null) {
continue;
} else if (firstRow.getCell(i).getStringCellValue().equals(str[j])) {
map.put(str[j], i);
flag++;
}
}
if (flag == 0) {
System.out.println("的标题名:" + str[j] + ":不存在");
map.clear();
break;
} else if (flag > 1) {
map.clear();
break;
}
flag = 0;
}
} else {
map.clear();
}
return map;
}