List Map data in excel using java

白昼怎懂夜的黑 提交于 2021-01-27 20:01:24

问题


Need help! I am trying to code a simple function that could return the data from an excel source. I am trying to create a list of Maps of data from excel file but the list that I am getting has the same values. All value are the same.

Here is my code:

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class ExcelReaderFinal {
    public static void main(String[] args) throws IOException {
        String path = "C:\\Users\\username\\Downloads\\TestFile.xlsx";
        FileInputStream fis = new FileInputStream(path);
        Workbook workbook = new XSSFWorkbook(fis);
        Sheet sheet = workbook.getSheetAt(0);
        int lastRow = sheet.getLastRowNum()-5;
        int lastColumn = 3;

        Map<String, Object> dataMap = new HashMap<String, Object>();
        ArrayList<Map<String, Object>> dataList = new ArrayList<>();

        for(int j=0; j<=lastRow; j++){


            for(int i=0; i<=lastColumn; i++) {

                Row row = sheet.getRow(4);
                Cell keyCell = row.getCell(i);
                Row val = sheet.getRow(5+j);
                Cell valueCell = val.getCell(i);

                String value = valueCell.getStringCellValue().trim();
                String key = keyCell.getStringCellValue().trim();
                dataMap.put(key, value);

            }
            dataList.add(dataMap);
        }
        System.out.println(dataList);
    }

}

my actual output is like this:

[{Negative Val=0, Account Number=121312C, Positive Val=20,000,000.00, Banko=RCBC}, {Negative Val=0, Account Number=121312C, Positive Val=20,000,000.00, Banko=RCBC}, {Negative Val=0, Account Number=121312C, Positive Val=20,000,000.00, Banko=RCBC}]

but my expected output is like this:

And here is my excel file source:

In Summary:

  1. I want to get all the data in excel file in list format
  2. that list should be sorted based on the arrangement of columns from excel.

Thank you so much!!

来源:https://stackoverflow.com/questions/65403394/list-map-data-in-excel-using-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!