您好,我已读取 Excel 文件中的数据,然后将该数据存储到数组列表中。每次我使用不同的文件运行程序时,我希望将 arraylist 存储在 eclipse 上的另一个类中。因此,我的包中将有另一个类来保存所有这些数组。抱歉,如果我解释得不够好,但我想运行这个程序并每次都获得一个新的数组列表,存储在包中的另一个文件中。
package Experiment1;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ReadExcel {
public static void main(String args[]) throws IOException{
FileInputStream fis = new FileInputStream(new File("C:/myfile"));
//create workbook instance that refers to .xlsx file
XSSFWorkbook wb = new XSSFWorkbook(fis);
//create a sheet object to retrieve the sheet
XSSFSheet sheet = wb.getSheetAt(0);
//this is for evaluate the cell type
FormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator();
//int rowStart = Math.min(1, sheet.getFirstRowNum());
//int rowEnd = Math.max(64, sheet.getLastRowNum());
ArrayList<Double> list = new ArrayList<Double>();
for(Row row : sheet){
for(Cell cell : row){
switch(formulaEvaluator.evaluateInCell(cell).getCellType())
{
case Cell.CELL_TYPE_NUMERIC:
list.add(cell.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING:
break;
}
}
/*for(int i = 0; i<list.size();i++){
System.out.println(list.get(i));
}
*/
}
}
}
最佳答案
好的,我想我已经明白你的意思了。
这项工作是将您的 ArrayList<Double> list
存储在同一包内的文件中。 .
了解Serialization in Java (IBM)和 its secrets (Oracle...) .
用 implements Serializable
声明你的类,为对象序列化添加生成的唯一标识符,添加一些必要的内容,例如 toString()
, hashCode()
等等方法...
现在您将能够使用 list.serialize()
执行您需要的操作方法或使用 InputStream
和OutputStream
就像文档中一样。
我刚刚找到了一些你会喜欢的东西here :
序列化:
package beginnersbook.com;
import java.util.ArrayList;
import java.io.*;
public class ArrayListSerialization {
public static void main(String [] args) {
ArrayList<String> al=new ArrayList<String>();
al.add("Hello");
al.add("Hi");
al.add("Howdy");
try {
FileOutputStream fos= new FileOutputStream("myfile");
ObjectOutputStream oos= new ObjectOutputStream(fos);
oos.writeObject(al);
oos.close();
fos.close();
} catch(IOException ioe) {
ioe.printStackTrace();
}
}
}
反序列化:
package beginnersbook.com;
import java.io.*;
import java.util.ArrayList;
public class DeSerializationClass {
public static void main(String [] args)
{
ArrayList<String> arraylist= new ArrayList<String>();
try {
FileInputStream fis = new FileInputStream("myfile");
ObjectInputStream ois = new ObjectInputStream(fis);
arraylist = (ArrayList) ois.readObject();
ois.close();
fis.close();
} catch(IOException ioe) {
ioe.printStackTrace();
return;
} catch(ClassNotFoundException c) {
System.out.println("Class not found");
c.printStackTrace();
return;
}
for(String tmp: arraylist) {
System.out.println(tmp);
}
}
}
关于java - 如何在每次运行时将从 Excel 文件读取的数据保存到新类中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35812162/