簡體   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