有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何使用java在excel中读取和写入值?

  • Sample Excel --> Sorry I'm not allowed to attached a image..
  • TC No. | Title | Result
  • 1 | State and Vin | Failed
  • 2 | State and Reg Code | Passed
  • 3 | Booking a Test Drive | Passed
public class sampleTest{
public static void main(String[] args) throws Exception {
         int iTest = 2, iTest2 = 3;
          if (iTest == iTest2){
              //It will pass a value into the excel (e.g. "Passed")
          }
          else{
             //It will pass a value into the excel (e.g. "Failed")
          }
    }

我的程序的目标是通过从测试中获得通过和失败的结果来生成报告。我这里的主要问题是如何从excel中读取结果,并将值“通过”或“失败”放在结果列下


共 (2) 个答案

  1. # 1 楼答案

    here下载apache poi jar 通过这些examples演示如何从java程序读取/写入xls数据 示例帮助代码:

    public static void main(String[] args) throws IOException {
            Workbook wb = new HSSFWorkbook(); 
            Sheet sheet = wb.createSheet("sheet");
            Row row = sheet.createRow((short) 0);
    
            row.createCell(0).setCellValue(1.2);
            row.createCell(1).setCellValue(wb.getCreationHelper().createRichTextString("This is a string"));
            row.createCell(2).setCellValue(true);
    
            FileOutputStream fileOut = new FileOutputStream("workbook.xls");
            wb.write(fileOut);
            fileOut.close();
        }
    

    这可能会帮助您开始。 整个流程是:

    1. 创建工作簿=>;主xls文件
    2. 然后创建一张图纸
    3. 然后创建一行
    4. 对于每一行,创建任意数量的单元格,并用不同的值填充单元格
    5. 像文件一样编写工作簿

    可以有多种类型的单元格,有关详细信息,请参见this。 要了解如何读取excel文件,请执行以下操作:

    InputStream myxls = new FileInputStream("workbook.xls");
            wb     = new HSSFWorkbook(myxls);
    
    
             sheet = wb.getSheetAt(0);       // first sheet
             row     = sheet.getRow(0);        // third row
            HSSFCell cell   = (HSSFCell) row.getCell((short)1);  // fourth cell
            if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
                System.out.println("The Cell was a String with value \" " + cell.getStringCellValue()+" \" ");
            } else if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
                System.out.println("The cell was a number " + cell.getNumericCellValue());
            } else {
                System.out.println("The cell was nothing we're interested in");
            }
    

    有关更多信息,请参见this

  2. # 2 楼答案

    通过将作为Excel文档界面的库。一个选项是Apache POI。Excel示例代码可以在here中找到

    另一个选择是Java Excel API