我已经编写了一个代码,可以读取Excel公式单元格中的数据并返回字符串,现在我想将字符串值列表写入特定的工作表和特定的列。有人可以给我提供示例代码片段。
例:将数据列表写入excel文件的“ C”列。
我的代码如下:

 @Test

    public void SampleCustNumFormat() throws Exception {
    String [][] myXL = getExcelData();

    //See what has been read from Excel
    for (int i=0; i<xRows; i++)
    {
      for (int j=3; j<xCols; j++)
      {
          System.out.println (" Cust Num " + myXL[i][j]);
      }
    }
}

public  String [][] getExcelData() throws Exception {
String [][] tabArray=null;
    FileInputStream fi = new FileInputStream("C:\\SCE docs\\Automation\\CustomerAccount_Information.xls");
    HSSFWorkbook myWB = new HSSFWorkbook(fi);
    HSSFSheet mySheet = myWB.getSheetAt(0);

    FormulaEvaluator evaluator = myWB.getCreationHelper().createFormulaEvaluator();

    xRows = mySheet.getLastRowNum()+1;
    xCols = mySheet.getRow(0).getLastCellNum();
    tabArray = new String [xRows][xCols];

    for (int i=0;i<xRows;i++)
    {
      HSSFRow row = mySheet.getRow(i);
      for (int j=3;j<xCols;j++)
      {
        HSSFCell cell = row.getCell(j);
        CellValue cellValue = evaluator.evaluate(cell);
        String value = evaluateFormula(cellValue);
        tabArray[i][j]=value;
      }
    }
  return tabArray;
   }

private String evaluateFormula(CellValue cellValue) throws Exception{
// TODO Auto-generated method stub

int type = cellValue.getCellType();
Object result=null;
switch (type) {

    case HSSFCell.CELL_TYPE_BOOLEAN:
      result = cellValue.getBooleanValue();
      break;
    case HSSFCell.CELL_TYPE_NUMERIC:
      result = cellValue.getNumberValue();
      break;
    case HSSFCell.CELL_TYPE_STRING:
      result = cellValue.getStringValue();
      break;
    case HSSFCell.CELL_TYPE_BLANK:
      break;
    case HSSFCell.CELL_TYPE_ERROR:
      break;

    // CELL_TYPE_FORMULA will never happen
    case HSSFCell.CELL_TYPE_FORMULA:
     break;
   }

  return result.toString();
   }
 }





My Output list of string values is :
 Cust Num CustAccNum
 Cust Num 2-23-456-7891
 Cust Num 2-00-006-7891
 Cust Num 2-03-456-7891
 Cust Num 2-00-234-5678
 Cust Num 2-00-023-4891
 Cust Num 2-00-234-7891
 Cust Num 2-00-345-6781

最佳答案

如果我清楚地理解您的问题,那么您只想在每一行的特定列中写入一些数据。如果是正确的,那么以下内容将使您高兴。

  //sheet is the excel sheet and data[] is the array of data you need to write.
  For (int i=0; i<=sheet.getLastRowNum(); i++)
      sheet.getRow(1).createCell(2).setCellValue(data[i]);


有关详细信息,请使用n0741337建议的快速guide link

10-08 06:46
查看更多