импортировать лист Excel в таблицу Guava - PullRequest
0 голосов
/ 07 ноября 2019

Можно ли импортировать Excel как объект таблицы гуавы, где таблица Excel содержит более 3 столбцов?

Запутавшись в этом, так как большинство примеров кода говорят только о 3 столбцах в листе, как видно из ссылки нижетоже

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

1 Ответ

1 голос
/ 07 ноября 2019

Вы неверно истолковали Table<R,C,V>. Это не три столбца, а R row, C olumn и V alue.

A Excel Таблица будет Table<String, String, Object>, где ключами строки являются R1, R2, R3, .. а ключи столбцов: C1, C2, C3, ... Объекты - это значения ячеек.

Когда мы получаем содержимое каждой ячейки как String, тогда таблица Excel будет иметь вид:

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

и содержимое ячейки будет помещено туда как:

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

При условии, что лист Excel подобен:

enter image description here

Следующий код получает все содержимое в таблицу Guava.

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();
 }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...