簡體   English   中英

Apache POI excel 准備讀取列從 A 到 N

[英]Apache POI excel ready read column from A to N

我通過使用 Apache POI 類從 Excel 表中讀取數據編寫了以下代碼。 目前它讀取行名+列名。

我想增強它以允許我輸入許多列名,以防我有很多數據列。

我需要幫助來了解如何增強它。

目前,它只讀取("rowName", "columnName")

測試數據可以在來自 columnA.....columnN 的 excel 表中水平增長我想要這樣的東西("rowName", "columnNameA" till "columnNameN....") 這可能嗎? 或者其他更好的建議??

 public class readexcel { //method defined for reading a cell @Keyword private static findData(String rowName, String columnName) throws IOException { String cellValue = ReadCellData(rowName, columnName); System.out.println(cellValue); } private static String ReadCellData(String rowName, String columnName) throws IOException { FileInputStream fis=new FileInputStream(RunConfiguration.getProjectDir() + "/Data Files/testmatrix.xlsx"); Workbook workbook=new XSSFWorkbook(fis); Sheet sheet = workbook.getSheetAt(0); Row firstRow = sheet.getRow(0); int rowNameColIdx = findColumnIdx("Automation TC", firstRow); int colNameColIdx = findColumnIdx(columnName, firstRow); Iterator<Row> rowIterator = sheet.iterator(); rowIterator.next(); while (rowIterator.hasNext()) { Row row = rowIterator.next(); if (rowName.equals(row.getCell(rowNameColIdx).getStringCellValue())) { return row.getCell(colNameColIdx).getStringCellValue(); } } return null; } private static int findColumnIdx(String text, Row row) { for (Cell cell : row) { if (text.equals(cell.getStringCellValue())) { return cell.getColumnIndex(); } } return -1; } }

讀取數據腳本

def exceldata = CustomKeywords.'test.readexcel.ReadCellData'("rowName", "columnName")

假設您的電子表格看起來像

| Test1 | Test 2 | Test C |
| A     | 1      | aa     |
| B     | 2      | bb     |

並且您希望能夠告訴我第 2 行中 Test2 和 Test C 的值,然后我建議您分兩步進行。 首先,構建從列名到列索引的映射。 其次,從一行中讀取特定的單元格。

由於您已標記我建議使用以下代碼:

int headerRowNumber = 0 // 0-based row numbering
Sheet sheet = wb.getSheetAt(0) // what sheet to read from

Map<String,Integer> colNamesToNumbers = [:]
DataFormatter fmt = new DataFormatter()

sheet.getRow(headerRowNumber).each { cell ->
   // Render the column heading to a string, in case it's a number
   String heading = fmt.formatCellValue(cell)
   colNamesToNumbers[heading] = cell.getColumnIndex()
}

然后做閱讀,像

Closure readValues = { int rowNum, List<String> columnNames ->
   Row row = sheet.getRow(rowNum)
   if (row == null) return []

   return columnNames.collect { String name ->
      int colNum = colNamesToNumbers[name]
      return fmt.formatCellValue( row.getCell(colNum) )
   }
}

List<String> valsRow2 = readValues(2, ["Test1","Test C"])
// returns ["B","bb"]
List<String> valsRow7 = readValues(7, ["Test 2"])
// returns [] as no row 7

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM