我寫了一個方法「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