package bboss; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import jxl.Cell; import jxl.Sheet; import jxl.Workbook; import jxl.read.biff.BiffException; /** * * @author llh * */ public class ExcelReadSOAP { /** * 使用jxl讀取excel中數據 * * @param args * @throws IOException * @throws BiffException */ public static String ExcelReadSOAP(String code) throws IOException, BiffException { int lie = 0; String retur = null; System.out.println("項目路徑" + System.getProperty("user.dir")); File file = new File(System.getProperty("user.dir") + "\\case\\編碼大全.xls"); System.out.println("文件路徑:" + file + "\n" + "文件絕對路徑:" + file.getAbsolutePath()); // 讀取xls文件流 InputStream is = new FileInputStream(file.getAbsolutePath()); // 使用jxl Workbook rwb = Workbook.getWorkbook(is); // 獲取當前excel中共有幾個表 Sheet[] sheets = rwb.getSheets(); // 獲取表數 int pages = sheets.length; System.out.println("表數:" + pages); for (int i = 0; i < pages; i++) { Sheet sheet = sheets[i]; // 有多少列 int cols = sheet.getColumns(); System.out.println("有" + cols + "列"); // 有多少行 int rows = sheet.getRows(); System.out.println("有" + rows + "行"); // 列循環 for (int j = 0; j < cols; j++) { //行循環 for(int k = 0 ; k <rows ; k++){ //定位坐標,從(0,0開始) Cell excelRows = sheet.getCell(j, k); //取坐標值 String e = excelRows.getContents(); //如果找到相應的交易編碼,保存所在列值 if(code.equals(e)){ lie = j; } } } //取出對應交易編碼的頭部信息並返回 retur = sheet.getCell(lie,0).getContents(); if(retur==null){ System.out.println("-----------在對應協議模板中未找到相對應的業務-----------"); } } return retur; } }
在項目中,我們經常會使用到excel來保存一些數據,所以在項目中,讀取excel中的內容也成為了我們必須要經常使用到的技術,在這里做一下記錄,為了方便自己隨時查看,也為了幫助大家需要這個方法的來借鑒。