importjava.io.FileInputStream;importjava.io.IOException;importjava.io.InputStream;importorg.apache.poi.hssf.usermodel.HSSFWorkbook;importorg.apache.poi.ss.usermodel.Cell;importorg.apache.poi.ss.usermodel.CellType;importorg.apache.poi.ss.usermodel.Row;importorg.apache.poi.ss.usermodel.Sheet;importorg.apache.poi.ss.usermodel.Workbook;public classDnsTest {public static void main(String[] args) throwsIOException{
getIdbyname("株洲");
getNamebyid(6) ;
}public static void getIdbyname(String name)throwsIOException {//通过name获得id
String filePath="D://dns.xls";
InputStream input= newFileInputStream(filePath);
Workbook wb= null;
wb= newHSSFWorkbook(input);//得到一个工作表对象;
Sheet sheet = wb.getSheetAt(0);int rsRows = sheet.getLastRowNum();//获取sheet表中的总行数//遍历行
for (int i=0;i<=rsRows;i++) {
System.out.println("遍历行数"+i);
Row row=sheet.getRow(i);int id=0;
String flag=null;//遍历行单元格,已知有两列;第一列int型id,第二列String型name
Cell cell1 = row.getCell(0);
Cell cell2= row.getCell(1);if(cell1==null||cell1.equals(null)||cell1.getCellType()==CellType.BLANK){
System.out.println("id为空");break;
}else{//数值型
id=(int) cell1.getNumericCellValue();
};if(cell2==null||cell2.equals(null)||cell2.getCellType()==CellType.BLANK){
System.out.println("name为空");break;
}else{//字符串型
flag=cell2.getStringCellValue();
};
String a=newString(flag);
String b=newString(name);if(a.equals(b)){
System.out.println(id);
};
}
wb.close();//记得关闭
}public static void getNamebyid(int id) throwsIOException {//通过id获得name
String filePath="D://dns.xls";
InputStream input= newFileInputStream(filePath);
Workbook wb= null;
wb= newHSSFWorkbook(input);//得到一个工作表对象;
Sheet sheet = wb.getSheetAt(0);int rsRows = sheet.getLastRowNum();//获取sheet表中的总行数//遍历行
for (int i=0;i<=rsRows;i++) {int flag=0;
String name=null;
Row row=sheet.getRow(i);//遍历行单元格
Cell cell1= row.getCell(0);
Cell cell2= row.getCell(1);if(cell1==null||cell1.equals(null)||cell1.getCellType()==CellType.BLANK){break;
}else{//数值型
flag=(int) cell1.getNumericCellValue();
}if(cell2==null||cell2.equals(null)||cell2.getCellType()==CellType.BLANK){break;
}else{//字符串型
name=cell2.getStringCellValue();
}if(flag==id){
System.out.println(name);
}
}
wb.close();//记得关闭
}
}