将 excel sheet 导入番石榴 Table

import excel sheet to Guava Table

是否可以将 excel 作为 guava table 对象导入,其中 excel sheet 包含超过 3 列?

对此感到困惑,因为大多数代码示例只讨论 sheet 中的 3 列,如下面 link 所示

https://www.geeksforgeeks.org/table-guava-java/

您误解了 Table<R,C,V>。这不是三列,而是 R行、C列和 V值。

A Excel table 将是 Table<String, String, Object>,其中行键为 R1、R2、R3、..,列键为 C1、C2、C3、...对象是单元格值。

当我们将每个单元格内容设为 String 时,那么 Excel table 将是:

Table<String, String, String> excelTable = HashBasedTable.create();

单元格内容会像这样放在那里:

excelTable.put("R" + r, "C" + c, value);

给定一个 Excel sheet 喜欢:

以下代码获取 Guava 的所有内容 Table。

import org.apache.poi.ss.usermodel.*;

import java.io.FileInputStream;

import java.util.Map;

import com.google.common.collect.HashBasedTable; 
import com.google.common.collect.Table; 

class ReadExcelToGuavaTable {

 public static void main(String[] args) throws Exception {

  Table<String, String, String> excelTable = HashBasedTable.create();

  Workbook workbook = WorkbookFactory.create(new FileInputStream("Excel.xlsx"));
  DataFormatter dataFormatter = new DataFormatter(java.util.Locale.US);
  FormulaEvaluator formulaEvaluator = workbook.getCreationHelper().createFormulaEvaluator();

  Sheet sheet = workbook.getSheetAt(0);
  int r = 1;
  int c = 1;
  for (Row row : sheet) {
   r = row.getRowNum() + 1;
   for (Cell cell : row) {
    c = cell.getColumnIndex() + 1;
    String value = dataFormatter.formatCellValue(cell, formulaEvaluator);
    //System.out.println("R" + r + "C" + c + " = " + value);
    excelTable.put("R" + r, "C" + c, value);
   }
  }

  // get Map corresponding to row 1 in Excel 
  Map<String, String> rowMap = excelTable.row("R1"); 
  System.out.println("List of row 1 content : "); 
  for (Map.Entry<String, String> row : rowMap.entrySet()) { 
   System.out.println("Column : " + row.getKey() + ", Value : " + row.getValue()); 
  } 

  // get a Map corresponding to column 4 in Excel
  Map<String, String> columnMap = excelTable.column("C4"); 
  System.out.println("List of column 4 content : "); 
  for (Map.Entry<String, String> column : columnMap.entrySet()) { 
   System.out.println("Row : " + column.getKey() + ", Value : " + column.getValue()); 
  } 

  // get single cell content R5C5
  System.out.println("Single cell content R5C5 :"); 
  System.out.println("R5C5 : " + excelTable.get("R5", "C5")); 

  // get all rows and columns
  Map<String,Map<String,String>> allMap = excelTable.rowMap();
  System.out.println("List of whole table : "); 
  for (Map.Entry<String, Map<String, String>> row : allMap.entrySet()) { 
   Map<String, String> colMap = row.getValue();
   for (Map.Entry<String, String> column : colMap.entrySet()) { 
    System.out.println(row.getKey() + column.getKey() + " = " + column.getValue()); 
   } 
  }   

  workbook.close();
 }
}