2016-12-19 41 views
0

我寫了一個函數,它使用POI將數據寫入到excel中。但是,目前我必須指定要在參數中寫入數據的行和列。我想讓這個函數通用,它應該自動在特定測試用例的下一列中寫入數據,並在測試用例更改時更改該行。在Excel中寫入的函數

public void WritetoExcel(String filepath,String DatatoWrite,int RowNum, int ColNum, int sheetnumber) throws Exception 
    { 
     FileInputStream ExcelFile = new FileInputStream(filepath); 
     ExcelWBook = new XSSFWorkbook(ExcelFile); 
     ExcelWSheet = ExcelWBook.getSheetAt(sheetnumber); 

     try{ 
      Row = ExcelWSheet.getRow(RowNum); 
      Cell = Row.getCell(ColNum, org.apache.poi.ss.usermodel.Row.RETURN_BLANK_AS_NULL); 
      if (Cell == null) { 
       Cell = Row.createCell(ColNum); 
       Cell.setCellValue(DatatoWrite); 
       } else { 
        Cell.setCellValue(DatatoWrite); 
       } 
      FileOutputStream fileOut = new FileOutputStream(filepath); 
       ExcelWBook.write(fileOut); 
       fileOut.flush(); 
       fileOut.close(); 
      }catch(Exception e){ 
       throw (e); 
      } 
     } 

有人可以幫我嗎我該怎麼做?

+0

你能指定測試用例嗎? – XtremeBaumer

+0

每次運行事務時,測試用例都要寫入orderID及其狀態。當測試用例再次運行時,會生成一個新的訂單ID及其相應的狀態,我想再次在Excel中寫入 –

+0

這個問題對我來說不是很清楚。你如何認識測試用例發生了變化,最新的標準是什麼?每當你寫1個單元格時,你的方法是不是叫做 – JDC

回答

0
public void WritetoExcel(String filepath, String DatatoWrite, int sheetnumber, boolean newTest) throws Exception { 
     FileInputStream ExcelFile = new FileInputStream(filepath); 
     ExcelWBook = new XSSFWorkbook(ExcelFile); 
     ExcelWSheet = ExcelWBook.getSheetAt(sheetnumber); 

     try { 
      if (newTest) { 
       Row = ExcelWSheet.createRow(RowNum++); 
       cellnum=0; 
      } 
      Cell = Row.creatCell(cellnum++); 
      Cell.setCellValue(DatatoWrite); 
      FileOutputStream fileOut = new FileOutputStream(filepath); 
      ExcelWBook.write(fileOut); 
      fileOut.flush(); 
      fileOut.close(); 
     } catch (Exception e) { 
      throw (e); 
     } 
    } 

因此,據我瞭解,你有一個空白的Excel表,你想填寫的數據。因此每次布爾值爲真時都需要創建一個新行,並且總是一個新的單元格。如果運行新的測試用例,布爾值僅爲true。使rownum和cellnum成員變量並將其值設置爲0.此代碼需要一個空的excel文件。