注意每個方法結束都要關閉workbook;
還有getIdbyname()方法中字符串flag與name的比較,一定要用equals()方法!!!;
剩下的不多解釋,注釋都在代碼中:
import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import org.apache.poi.hssf.usermodel.HSSFWorkbook; 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; public class DnsTest { public static void main(String[] args) throws IOException{ getIdbyname("株洲"); getNamebyid(6) ; } public static void getIdbyname(String name)throws IOException { //通過name獲得id String filePath="D://dns.xls"; InputStream input = new FileInputStream(filePath); Workbook wb = null; wb = new HSSFWorkbook(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=new String(flag); String b=new String(name); if(a.equals(b)){ System.out.println(id); }; } wb.close();//記得關閉 } public static void getNamebyid(int id) throws IOException { //通過id獲得name String filePath="D://dns.xls"; InputStream input = new FileInputStream(filePath); Workbook wb = null; wb = new HSSFWorkbook(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();//記得關閉 } }