我写了一个方法“writeData”,将apache poi将现有excel文件中的列数据写入新的excel文件。它运作良好。但是当我尝试再次调用此方法时,以前的数据丢失了。为什么?有人可以帮助我吗?为什么在我再次写入该文件后,由excel文件中的poi写入的数据缺失?
public class ReadData {
/**
* @param args
*/
Workbook wb, wb1;
Sheet sheet, sheet1;
Row row;
Row row1;
static int cell;
Cell cell1;
static ArrayList<Cell> list1 = new ArrayList<Cell>();
static ArrayList<Cell> list2 = new ArrayList<Cell>();
public static ArrayList<Cell> readData(String filename, int cellNum, ArrayList array){
try{
InputStream inp = new FileInputStream(filename);
Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt(0);
for (int j=sheet.getLastRowNum(); j>0; j--) {
Row row = sheet.getRow(j);
Cell cell = row.getCell(cellNum);
array.add(cell);
System.out.println(cell);
}
}catch(Exception e){
System.out.println("Wrong!" + e.getMessage());
e.getStackTrace();
System.out.println(e.getStackTrace());
}
return array;
}
public static void writeData(int cellNo, ArrayList<Cell> array){
Workbook wb1 = new HSSFWorkbook();
FileOutputStream fos = null;
try{
fos = new FileOutputStream("3.xls");
Sheet sheet1 = wb1.createSheet("Data");
for(int i = 0; i < array.size(); i++){
Row row1 = sheet1.createRow(i);
Cell cell1 = row1.createCell(cellNo);
cell1.setCellValue(array.get(i).getNumericCellValue());
}
wb1.write(fos);
fos.close();
}catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
readData("1.xls",0,list1);
writeData(0,list1);
readData("2.xls",0,list2);
writeData(1,list2);
}
}
你总是覆盖以前的文件:你正在使用一个固定的文件名,并且每次运行'writeData()时重新创建一个新文件' – 2012-08-10 17:42:49
那么你知道如何解决它吗? – 2012-08-10 19:18:35
这将取决于预期的行为。好像你应该对readData()进行所有的调用,建立你的数据集,然后把它写在一个单独的Excel文件中。我从来没有使用POI,所以不能评论。 – 2012-08-10 20:01:38