2012-08-10 91 views
0

我写了一个方法“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); 
} 

} 
+0

你总是覆盖以前的文件:你正在使用一个固定的文件名,并且每次运行'writeData()时重新创建一个新文件' – 2012-08-10 17:42:49

+0

那么你知道如何解决它吗? – 2012-08-10 19:18:35

+0

这将取决于预期的行为。好像你应该对readData()进行所有的调用,建立你的数据集,然后把它写在一个单独的Excel文件中。我从来没有使用POI,所以不能评论。 – 2012-08-10 20:01:38

回答

0

你的问题是,你从头开始您的工作簿和FileOuputStream覆盖您的文件。

您需要打开将其链接到您的文件的工作簿。为此,构建你的Excel和InputStream。

InputStream input = new FileInputStream("3.xls"); 
wb1 = new HSSFWorkbook(input); 

对于写作,我不完全相信,如果你真的需要使用FileOuputStream,也许正确关闭工作簿就足够了(与XSSFWorkbooks作品)。

OutputStream将工作,但如果输入等于输出,则可能会出现一些错误。

希望它帮助。

+0

感谢您的帮助。我有另一个问题。你知道如何实现不包括在poi评估列表中的excel函数,比如斜率吗? “SLOPE”是excel中的常规函数​​,但我无法通过poi评估它。 – 2012-08-13 12:06:50

+0

有特定的工具来评估公式(目前只有pn HSSF工作簿)。见[这个问题](http://stackoverflow.com/questions/5747034/poi-formula-evaluation?answertab=votes#tab-top)如果没有在列表中,唯一的方法是自己评估它..祝你好运。 – ArtiBucco 2012-08-13 12:40:22