簡體   English   中英

如何在 Apache Camel 中創建 Excel (.xlsx) 文件?

[英]How to create an Excel (.xlsx) file in Apache Camel?

我正在嘗試創建一個 Excel 文件並使用 Apache Camel 將其發送到 SFTP 位置。 我可以像這樣從 Java 對象創建 PSV:

Java POJO:

 @CsvRecord(separator = ",", skipFirstLine = true, generateHeaderColumns = true)
public class IexPerson implements Serializable {

   private static final long serialVersionUID = 1234069326527342909L;

    @DataField(pos = 1, columnName = "Person Name")
    private String personName;
    @DataField(pos = 2, columnName = "Gender")
    private String gender;

  // other fields ...

然后我轉換路線中的 IexPersons 列表:

DataFormat iexPersonFormat = new BindyCsvDataFormat(IexPerson.class);

from("direct-get-list-of-persons")
   .setHeader(Exchange.FILE_NAME).simple("Persons_${date:now:yyyyMMdd-HHmmssSSS}_${random(1000,10000000)}.csv")
   .marshal(iexPersonFormat)
   .to("file:///tmp?fileName=${header.CamelFileName}");

這工作正常,但現在我需要從同一個列表創建一個 Excel 文件並將其發送到另一個位置。 我沒能讓它工作。 我沒有在互聯網上找到任何可以幫助我的東西。

我通常使用XSL 轉換來創建Microsoft Office XML 格式的 Excel 文件。

您可以在鏈接的 Wikipedia 頁面上找到 Excel 電子表格的示例 XML。

但是,我通常會創建一個簡單的Excel 文件來表示我想要的內容,然后將其保存為 "XML Spreadsheet 2003"

結果是我需要使用 XSL 樣式表生成的 XML 文件結構

在此處為在同一主題上需要幫助的未來用戶發布。 通過使用Apache POI庫,我能夠將 Java 對象轉換為工作的 excel 文件。

我創建了一個服務,並在其中創建了一個將對象轉換為文件的方法,我從我的 Camel 路由中調用了該方法。 在這里得到了很好的解釋。

這是代碼:

  // Create a blank Workbook
  try (Workbook workbook = new XSSFWorkbook()) {

  // Create a blank Sheet
  Sheet sheet = workbook.createSheet("IexPersons");

  // column names
  List <String> columns = new ArrayList<>();
  columns.add("Person Name");
  columns.add("Gender");

  Row headerRow = sheet.createRow(0);

  // Create columns/first row in a file
  for (int i = 0; i < columns.size(); i++) {
    Cell cell = headerRow.createCell(i);
    cell.setCellValue(columns.get(i));
  }

  int rowNum = 1;

  // iterate over the list of persons and for each person write its values to the excel row
  for (IexPerson iexPerson : getListOfPersons()) {
    Row row = sheet.createRow(rowNum++);

    // populate file with the values for each column
    row.createCell(0).setCellValue(iexPerson.getName());
    row.createCell(1).setCellValue(iexPerson.getGender());
  }

  // create file
  FileOutputStream out = new FileOutputStream(new File("iexpersons.xlsx"));

  // write data to file
  workbook.write(out);

  // close the output stream
  out.close();

} catch (IOException e) {
  e.printStackTrace();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM