/**
* 读取excel表格中特定的列
*
* @param file 文件
* @param index 第index列(0开始)
* @throws Exception
*/
public static void readColumn(File file, int index) throws Exception {
InputStream inputStream = new FileInputStream(file.getAbsoluteFile());
Workbook workbook = WorkbookFactory.create(inputStream);
Sheet sheet = workbook.getSheetAt(2);
// 定义一个map用于存放excel列的序号和field.
Map<String, Integer> cellMap = new HashMap<String, Integer>();
// 所有行
int num = sheet.getPhysicalNumberOfRows();
List col1 = new ArrayList<String>();
List col2 = new ArrayList<String>();
for (int i = 1; i < num; i++) {
for (int j = sheet.getRow(i).getFirstCellNum(); j < sheet.getRow(i).getLastCellNum(); j += 5) {
if (j<5){
short lastCellNum = sheet.getRow(i).getLastCellNum();
Row header = sheet.getRow(i);
Cell cell = header.getCell(j);
cell.getStringCellValue();
System.out.println(cell.getStringCellValue());
col1.add(cell.getStringCellValue().trim());
}else {
short lastCellNum = sheet.getRow(i).getLastCellNum();
Row header = sheet.getRow(i);
Cell cell = header.getCell(j);
cell.getStringCellValue();
System.out.println(cell.getStringCellValue());
col2.add(cell.getStringCellValue().trim());
}
}
}
List col3 = new ArrayList<String>();
for (int i =0; i< col1.size(); i++){
if (!col2.contains(col1.get(i))){
col3.add(col1.get(i));
}
}
System.out.println("============新增公司如下===========");
for (int i =0; i<col3.size(); i++){
System.out.println(col3.get(i));
}
System.out.println("col1 size:" + col1.size());
System.out.println("col2 size:" + col2.size());
System.out.println("col3 size:" + col3.size());
}
原理:
先获取所有行数,每一行为一个cell,然后遍历每个cell,得到每一行的每一列。
思考:
能不能直接获取某个sheet页的某一列呢。待考证。。。。