Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/340.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用POI Apache从Excel读取数据时向ArrayList添加数据_Java_Excel_Arraylist_Apache Poi - Fatal编程技术网

Java 使用POI Apache从Excel读取数据时向ArrayList添加数据

Java 使用POI Apache从Excel读取数据时向ArrayList添加数据,java,excel,arraylist,apache-poi,Java,Excel,Arraylist,Apache Poi,我正在尝试使用POI Apache从Excel工作表读取数据。我遇到的问题是,我希望同时读取一行中所有单元格的数据,并将其存储在类类型的ArrayList中,但输出仅是逐单元格的 package testing; import javax.swing.JFileChooser; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.Array

我正在尝试使用POI Apache从Excel工作表读取数据。我遇到的问题是,我希望同时读取一行中所有单元格的数据,并将其存储在类类型的ArrayList中,但输出仅是逐单元格的

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();
        }
    }
}
下面是打开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();
        }
    }
}

我想在Arraylist中一次性添加这样的单元格数据

List.add(new Data(1,"Amit","shukla"));
但是迭代器返回的数据是一个接一个的,它首先输出1,然后输出amit,然后输出shukla,这很难添加到arraylist中

我试着在一行向ArrayList添加数据,但是我做不到。如果你们能帮我解决这个问题,那将非常有帮助。

this.path=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();
    }
试试看
{
FileInputStream file=newfileinputstreahashmapile(路径));
HashMap mp=新的HashMap();
//创建包含对.xlsx文件引用的工作簿实例
XSSF工作簿=新XSSF工作簿(文件);
//从工作簿中获取第一张/所需的工作表
XSSFSheet sheet=workbook.getSheetAt(0);
System.out.println(“”);
//逐个遍历每一行
迭代器rowIterator=sheet.Iterator();
while(roweiterator.hasNext())
{
行=行迭代器。下一步();
//对于每一行,遍历所有列
迭代器cellIterator=row.cellIterator();
while(cellIterator.hasNext())
{
Cell=cellIterator.next();
//检查相应的单元格类型和格式
int i=0;
int j=0;
开关(cell.getCellType())
{
case Cell.Cell\u类型\u数值:
System.out.print(cell.getNumericCellValue()+“\t”);
i=Integer.parseInt(cell.getNumericCellValue());
数据d=新数据();
d、 setId(cell.getNumericCellvalue());
打破
case Cell.Cell\u类型\u字符串:
System.out.print(cell.getStringCellValue()+“\t”);
如果(j==0){
数据=mp.get(i);
data.setName(cell.getStringCellValue());
mp.put(一、数据);
j=j+1;
}
其他的
{
数据=mp.get(i);
data.setLastName(cell.getStringCellValue());
mp.put(一、数据);
j=0;
}
打破
}
}
System.out.println(“”);
}
List dataList=new ArrayList();
对于(数据d:mp.values()){
数据表.添加(d);
}
file.close();
} 
捕获(例外e)
{
e、 printStackTrace();
}

您可以通过一次迭代来添加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());
        }
        }

}
public void ReadExcel(字符串文件路径、字符串文件名、字符串表名)引发InterruptedException、IOException{
文件文件=新文件(文件路径+“\\”+文件名);
//创建FileInputStream类的对象以读取excel文件
FileInputStream inputStream=新的FileInputStream(文件);
工作簿AddCatalog=null;
//通过在子字符串中拆分文件名并仅获取扩展名来查找文件扩展名
字符串fileExtensionName=fileName.substring(fileName.indexOf(“.”);
//检查文件是.xls文件还是.xlsx文件的条件
if(fileExtensionName.equals(“.xls”)){
//如果是.xls文件,则创建HSSFWorkbook类的对象
AddCatalog=新的HSSF工作簿(inputStream);
}
else if(fileExtensionName.equals(“.xlsx”)){
//如果是.xlsx文件,则创建XSSFWorkbook类的对象
AddCatalog=新XSSF工作簿(inputStream);
}
//按工作表的名称阅读工作表
图纸AddCatalogSheet=AddCatalog.getSheet(图纸名称);
//查找excel文件中的行数
int rowcount=AddCatalogSheet.getLastRowNum()-AddCatalogSheet.getFirstRowNum();
System.out.println(“总行数:“+rowcount”);

对于(int i=1;i您在开关和案例中遇到问题,对此进行零件更改应该可以:

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

难道你不能将setter添加到数据类中,并在循环遍历一行中的所有单元格时相应地构建它,然后在该行完成后将其添加到arrayList吗?创建一个HashMap,该HashMap将保存id和数据对象,然后将值转换为List,dataList将具有所需的对象列表