How to read and write excel file

后端 未结 22 2991
北荒
北荒 2020-11-22 04:49

I want to read and write an Excel file from Java with 3 columns and N rows, printing one string in each cell. Can anyone give me simple code snippet for this? Do I need to

22条回答
  •  没有蜡笔的小新
    2020-11-22 05:13

    Another way to read/write Excel files is to use Windmill. It provides a fluent API to process Excel and CSV files.

    Import data

    try (Stream rowStream = Windmill.parse(FileSource.of(new FileInputStream("myFile.xlsx")))) {
      rowStream
        // skip the header row that contains the column names
        .skip(1)
        .forEach(row -> {
          System.out.println(
            "row n°" + row.rowIndex()
            + " column 'User login' value : " + row.cell("User login").asString()
            + " column n°3 number value : " + row.cell(2).asDouble().value() // index is zero-based
          );
        });
    }
    

    Export data

    Windmill
      .export(Arrays.asList(bean1, bean2, bean3))
      .withHeaderMapping(
        new ExportHeaderMapping()
          .add("Name", Bean::getName)
          .add("User login", bean -> bean.getUser().getLogin())
      )
      .asExcel()
      .writeTo(new FileOutputStream("Export.xlsx"));
    

提交回复
热议问题