将excel表格导入番石榴表
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了将excel表格导入番石榴表相关的知识,希望对你有一定的参考价值。
是否有可能将excel导入为excel表包含多于3列的番石榴表对象?
对此感到困惑,因为大多数代码示例都只讨论表单中的3列,如以下链接所示
答案
您误解了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
表,例如:
下面的代码将所有内容都保存到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();
}
}
以上是关于将excel表格导入番石榴表的主要内容,如果未能解决你的问题,请参考以下文章