简体   繁体   English

使用 POI Apache 从 Excel 读取数据时将数据添加到 ArrayList

[英]Adding data to ArrayList while reading data from Excel using POI Apache

I am trying to read data from Excel sheets using POI Apache.我正在尝试使用 POI Apache 从 Excel 工作表中读取数据。 The problem I am having is that I want to read the data of all cell of a row at the same time and store it in ArrayList of Type Class but the output is only cell by cell.我遇到的问题是我想同时读取一行的所有单元格的数据并将其存储在类型类的 ArrayList 中,但输出只是逐个单元格的。

Here is the class that open the excel sheet and read the data cell by cell.这是打开 excel 表并逐个单元格读取数据的类。

package testing;

import javax.swing.JFileChooser;
import java.io.File;
import java.io.FileInputStream;

import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
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.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ReadExcelDemo 
{
    ArrayList<Data> list = new ArrayList<>();
    String path;

   public ReadExcelDemo(String path)
   {
       this.path = path;

        try
        {
            FileInputStream file = new FileInputStream(new File(path));

            //Create Workbook instance holding reference to .xlsx file
            XSSFWorkbook workbook = new XSSFWorkbook(file);

            //Get first/desired sheet from the workbook
            XSSFSheet sheet = workbook.getSheetAt(0);

             System.out.println("");

            //Iterate through each rows one by one
            Iterator<Row> rowIterator = sheet.iterator();
            while (rowIterator.hasNext()) 
            {
                Row row = rowIterator.next();
                //For each row, iterate through all the columns
                Iterator<Cell> cellIterator = row.cellIterator();

                while (cellIterator.hasNext()) 
                {
                    Cell cell = cellIterator.next();
                    //Check the cell type and format accordingly
                    switch (cell.getCellType()) 
                    {
                        case Cell.CELL_TYPE_NUMERIC:
                            System.out.print(cell.getNumericCellValue() + "\t");

                            break;
                        case Cell.CELL_TYPE_STRING:
                            System.out.print(cell.getStringCellValue() + "\t");
                            break;
                    }
                }


                System.out.println("");
            }
            file.close();
        } 
        catch (Exception e) 
        {
            e.printStackTrace();
        }
    }
}

Data Class数据类

package testing;


public class Data {


    int ID;
    String F_Name,L_Name;




    public Data(int ID, String F_Name, String L_Name) {
        this.ID = ID;
        this.F_Name = F_Name;
        this.L_Name = L_Name;
    }


    public int getID() {
        return ID;
    }

    public String getF_Name() {
        return F_Name;
    }

    public String getL_Name() {
        return L_Name;
    }

在此处输入图像描述

I want to add the cell data in Arraylist like this at a single time我想像这样一次在 Arraylist 中添加单元格数据

List.add(new Data(1,"Amit","shukla"));

but the data the iterator return is one by one like first it outputs 1 then amit and then shukla which is really difficult to add to arraylist但是迭代器返回的数据是一个接一个,首先它输出1 ,然后是amit ,然后是shukla ,这真的很难添加到 arraylist

I tried so much to add data to ArrayList at a single line but I couldn't.我试图在一行中向 ArrayList 添加数据,但我做不到。 It would be really helpful if you guy help me solve this problem.如果你能帮我解决这个问题,那将非常有帮助。

this.path = path; this.path = 路径;

    try
    {
        FileInputStream file = new FileInputStreaHashMap<K, V>ile(path));
        HashMap<Integer, Data> mp= new HashMap<Integer, Data>();
        //Create Workbook instance holding reference to .xlsx file
        XSSFWorkbook workbook = new XSSFWorkbook(file);

        //Get first/desired sheet from the workbook
        XSSFSheet sheet = workbook.getSheetAt(0);

         System.out.println("");

        //Iterate through each rows one by one
        Iterator<Row> rowIterator = sheet.iterator();
        while (rowIterator.hasNext()) 
        {
            Row row = rowIterator.next();
            //For each row, iterate through all the columns
            Iterator<Cell> cellIterator = row.cellIterator();

            while (cellIterator.hasNext()) 
            {
                Cell cell = cellIterator.next();
                //Check the cell type and format accordingly
                int i=0;
                int j=0;
                switch (cell.getCellType()) 
                {
                    case Cell.CELL_TYPE_NUMERIC:
                        System.out.print(cell.getNumericCellValue() + "\t");
                            i=Integer.parseInt(cell.getNumericCellValue());
                            Data d= new Data();
                            d.setId(cell.getNumericCellvalue());


                        break;
                    case Cell.CELL_TYPE_STRING:
                        System.out.print(cell.getStringCellValue() + "\t");
                        if( j==0){
                        Data data= mp.get(i);
                        data.setName(cell.getStringCellValue());
                        mp.put(i, data);
                        j=j+1;
                        }
                        else
                        {
                            Data data= mp.get(i);
                            data.setLastName(cell.getStringCellValue());
                            mp.put(i, data);
                            j=0;
                        }
                        break;
                }
            }


            System.out.println("");
        }
        List<Data> dataList=  new ArrayList<Data>();
        for (Data d : mp.values()) {
           dataList.add(d);

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

You can add a single row of an excel sheet by a single iteration using this,您可以使用此功能通过单次迭代添加单行 Excel 工作表,

public void ReadExcel(String filePath,String fileName,String sheetName) throws InterruptedException, IOException{
    File file = new File(filePath+"\\"+fileName);
    //Create an object of FileInputStream class to read excel file
    FileInputStream inputStream = new FileInputStream(file);
    Workbook AddCatalog = null;
    //Find the file extension by splitting file name in substring  and getting only extension name
    String fileExtensionName = fileName.substring(fileName.indexOf("."));
    //Check condition if the file is a .xls file or .xlsx file
    if(fileExtensionName.equals(".xls")){
        //If it is .xls file then create object of HSSFWorkbook class
        AddCatalog = new HSSFWorkbook(inputStream);
    }
    else if(fileExtensionName.equals(".xlsx")){
        //If it is .xlsx file then create object of XSSFWorkbook class
        AddCatalog = new XSSFWorkbook(inputStream);
    }
    //Read sheet inside the workbook by its name
    Sheet AddCatalogSheet = AddCatalog.getSheet(sheetName);
    //Find number of rows in excel file
    int rowcount = AddCatalogSheet.getLastRowNum()- AddCatalogSheet.getFirstRowNum();
    System.out.println("Total row number: "+rowcount);
    for(int i=1; i<rowcount+1; i++){
        //Create a loop to get the cell values of a row for one iteration
        Row row = AddCatalogSheet.getRow(i);
        List<String> arrName = new ArrayList<String>();
        for(int j=0; j<row.getLastCellNum(); j++){
            // Create an object reference of 'Cell' class
            Cell cell = row.getCell(j);
            // Add all the cell values of a particular row
            arrName.add(cell.getStringCellValue());
            }
        System.out.println(arrName);
        System.out.println("Size of the arrayList: "+arrName.size());
        // Create an iterator to iterate through the arrayList- 'arrName'
        Iterator<String> itr = arrName.iterator();
        while(itr.hasNext()){
            System.out.println("arrayList values: "+itr.next());
        }
        }

}

You have a problem in Switch and Case part change to this should work :您在Switch 和 Case部分更改时遇到问题应该可以:

   switch (cell.getCellType())  {
         case NUMERIC:
               System.out.print(cell.getNumericCellValue() + "\t");
               break;
        case STRING:
              System.out.print(cell.getStringCellValue() + "\t");
              break;
      }

The easiest way to achieve this as follows实现此目的的最简单方法如下

  1. Create an array list with all the excel column names.创建一个包含所有 excel 列名的数组列表。
  2. Create a list for holding each row as an object创建一个列表,将每一行作为一个对象保存
  3. Create a HashMap for holding column name and cell value as key value pair创建一个 HashMap 用于保存列名和单元格值作为键值对
  4. Iterate through each row and iterate to each cell of that row.遍历每一行并迭代到该行的每个单元格。 and pull the cell values into the HashMap we created并将单元格值拉入我们创建的 HashMap
  5. After reading all the cells of current row, map this HashMap to custom pojo class using Jackson object mapper.读取当前行的所有单元格后,使用 Jackson 对象映射器将此 HashMap 映射到自定义 pojo 类。 And add this object to the list that we created in step 2.并将这个对象添加到我们在步骤 2 中创建的列表中。
  6. now repeat the step 4 and 5.现在重复步骤 4 和 5。

You can refer to the code below你可以参考下面的代码

                //declare list of column headers in the excel file
            List<String> header = new ArrayList<>(Arrays.asList("ID","FirstName","LastName"));
            //list for holding each row of data as list of custom objects
            List<CustomObject> rawDataList = new ArrayList<>();
            while (rowIterator.hasNext()) {

                Row row = rowIterator.next();
                //map for holding cell values of current row as key value pair
                Map<String, String> rowDataMap = new HashMap<>();
                Cell cell;
                for (int k = 0; k < row.getLastCellNum(); k++) {

                    if (null != (cell = row.getCell(k))) {
                        switch (cell.getCellType()) {
                        case NUMERIC:
                            //Get the column name from header array and push the cell value into hashmap
                            rowDataMap.put(header.get(k),NumberToTextConverter.toText(cell.getNumericCellValue()));
                            break;
                        case STRING:
                            //Get the column name from header array and push the cell value into hashmap
                            rowDataMap.put(header.get(k), cell.getStringCellValue());
                            break;

                        }
                    }
                }                   
                //create object of jackson object mnapper (Better configure as a bean)
                ObjectMapper mapper = new ObjectMapper()
                          .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
                mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
                mapper.configure(DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT, true);
                
                // after reading all the cells of current row map the hashmap into 
                //custom pojo class using object mapper 
                CustomObject rawData = mapper.convertValue(rowDataMap, CustomObject.class);
                //add the cusom pojo object into the list
                rawDataList.add(rawData);

            }

暂无
暂无

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

相关问题 如何使用Apache POI用来自数组列表的数据填充Excel工作表 - How to populate an Excel sheet with the data from an arraylist using Apache POI 使用Apache POI将ArrayList中的数据插入Excel文件中的块中 - Inserting data from arraylist in chunks in excel file using apache poi 使用apache poi从扩展名为xlsx的Excel文件中读取数据时,需要花费很长时间 - While Reading the data from Excel file with extension xlsx using apache poi it takes long time 使用Apache POI向Excel文件写入来自字符串数组列表的大量数据 - Writing to an Excel file using Apache POI a huge data from ArrayList of Strings 线程“ main”中的异常org.apache.poi.POIXMLException使用apache POI从xlsx文件读取数据时出现异常 - Exception in thread “main” org.apache.poi.POIXMLException exception appearing while reading data from xlsx file using apache POI 使用Apache poi从Excel读取数据后,java.lang.NullPointerException错误 - java.lang.NullPointerException error after reading data from Excel using Apache poi POI从excel读取数字数据时附加.0 - POI Appending .0 while reading numeric data from excel 使用apache POI和java访问excel数据时出错 - Getting error while accessing excel data using apache POI and java 使用Apache POI从Excel读取单元格 - Reading a cell from Excel using Apache POI 为什么使用 poi api java 从 excel 文件读取数据时格式会发生变化? - Why format changes while reading data from excel file using poi api java?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM