将excel表格导入番石榴表

问题描述 投票:0回答:1

是否有可能将excel导入为excel表包含多于3列的番石榴表对象?

对此感到困惑,因为大多数代码示例都只讨论表单中的3列,如以下链接所示

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

excel apache-poi guava
1个回答
1
投票

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

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();
 }
}
© www.soinside.com 2019 - 2024. All rights reserved.