繁体   English   中英

如何从.xlsx读取数据并将数据转换成map

[英]How to read the data from .xlsx and convert the data into map

我需要从 Excel 表中读取数据,并且需要将数据转换为键值对。

我写了下面的代码。

这是我的代码:

import java.io.File;  
import java.io.FileInputStream;  
import java.util.Iterator;  
import org.apache.poi.ss.usermodel.Cell;  
import org.apache.poi.ss.usermodel.Row;  
import org.apache.poi.xssf.usermodel.XSSFSheet;  
import org.apache.poi.xssf.usermodel.XSSFWorkbook;  

public class XLSXReaderExample  {  
    public static void main(String[] args) {  
       try {  
          File file = new File("C:\\demo\\employee.xlsx");   //creating a new file instance  
          FileInputStream fis = new FileInputStream(file);   //obtaining bytes from the file  
          //creating Workbook instance that refers to .xlsx file  
          XSSFWorkbook wb = new XSSFWorkbook(fis);   
          XSSFSheet sheet = wb.getSheetAt(0);     //creating a Sheet object to retrieve object  
          Iterator<Row> itr = sheet.iterator();    //iterating over excel file  
          while (itr.hasNext()){  
             Row row = itr.next();  
             Iterator<Cell> cellIterator = row.cellIterator();   //iterating over each column  
             while (cellIterator.hasNext()){  
                Cell cell = cellIterator.next();  
                switch (cell.getCellType()){  
                   case Cell.CELL_TYPE_STRING:    //field that represents string cell type  
                      System.out.print(cell.getStringCellValue() + "\t\t\t");  
                      break;  
                   case Cell.CELL_TYPE_NUMERIC:    //field that represents number cell type  
                      System.out.print(cell.getNumericCellValue() + "\t\t\t");  
                      break;  
                   case Cell.CELL_TYPE_Date:    //field that represents Date cell type
                      System.out.print(cell.getDateCellValue() + "\t\t\t");  
                      break; 
                   default:  
                }  
             }  
             System.out.println("");  
          }  
       }catch(Exception e){  
          e.printStackTrace();  
       }  
    }  
 } 

我得到 output 如下:

Employee ID   Employee Name    Salary     Designation          Department   
1223.0         Harsh                      Marketing Manager    Marketing
3213.0         Vivek           15000.0    Financial Advisor    Finance  

但是,我需要 output,因为所有 header 列都应该出现在 map 键中,并且相应的数据应该作为值出现。 还有一件事是我不应该对列名进行硬编码,每次列标题可以不同时,我都需要动态地从 Excel 读取。

我需要将我的数据设置为以下格式,请帮助。 Map<String, List<String>> myMaps = new HashMap<String, List<String>>();

正如评论中所写,由于您无法知道单元格是否包含 header 值或数据值,因此您想要做的事情是不可能的。

乍一看,您有两种方法可以实现您想要的:

  • 尝试让文件只有一个表,并且 header 行必须始终位于同一 excel 行(请参见此处)
  • 为 header 添加自定义标签内容:如<H> </H> ,但当然如果文件在可视化模式下使用,这个解决方案不是最好的

编辑:

您添加了一条注释,确认 header 始终位于第一行,并且文件中只有一个表,因此下一个代码应该可以工作。

public static void main(String[] args) {
    try {
        File file = new File("C:\\demo\\employee.xlsx");   //creating a new file instance
        FileInputStream fis = new FileInputStream(file);   //obtaining bytes from the file
        //creating Workbook instance that refers to .xlsx file
        XSSFWorkbook wb = new XSSFWorkbook(fis);
        XSSFSheet sheet = wb.getSheetAt(0);     //creating a Sheet object to retrieve object
        Iterator<Row> itr = sheet.iterator();    //iterating over excel file

        // CAREFUL HERE! use LinkedHashMap to guarantee the insertion order!
        Map<String, List<String>> myMap = new LinkedHashMap<>();

        // populate map with headers and empty list
        if (itr.hasNext()) {
            Row row = itr.next();
            Iterator<Cell> headerIterator = row.cellIterator();
            while (cellIterator.hasNext()) {
                Cell cell = cellIterator.next();
                myMap.put(getCellValue(cell), new ArrayList<>());
            }
        }

        Iterator<List<String>> columnsIterator;
        // populate lists
        while (itr.hasNext()) {

            // get the list iterator every row to start from first list
            columnsIterator = myMap.values().iterator();
            Row row = itr.next();
            Iterator<Cell> cellIterator = row.cellIterator();   //iterating over each column
            while (cellIterator.hasNext()) {
                Cell cell = cellIterator.next();

                // here don't check hasNext() because if the file not contains problems
                // the # of columns is same as # of headers
                columnsIterator.next().add(getCellValue(cell));
            }
        }

        // here your map should be filled with data as expected

    } catch (Exception e) {
        e.printStackTrace();
    }
}

public static String getCellValue(Cell cell) {
    switch (cell.getCellType()) {
        case Cell.CELL_TYPE_STRING:    //field that represents string cell type
            return cell.getStringCellValue() + "\t\t\t";
        case Cell.CELL_TYPE_NUMERIC:    //field that represents number cell type
            return cell.getNumericCellValue() + "\t\t\t";
        case Cell.CELL_TYPE_Date:    //field that represents Date cell type
            return cell.getDateCellValue() + "\t\t\t";
        default:
            return "";
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM