【问题标题】:Generating csv file for multiple loop in Java?在Java中为多个循环生成csv文件?
【发布时间】:2021-09-05 19:22:27
【问题描述】:

我正在尝试使用如下所示的级联值生成报告:

| Country      | City     | Town     |
--------------------------------------
| Country A    | City X   | Town 1   |
| Country A    | City X   | Town 2   |
| Country A    | City Y   | Town 1   |
| Country A    | City Y   | Town 2   |
| Country B    | City Q   | Town 1   |
| Country B    | City Q   | Town 2   |
| Country B    | City T   | Town 1   |
| Country B    | City T   | Town 2   |


我可以正确生成如上所示的 Country 和 City,但我为每个城市传递了一个 j 索引值,如下所示。但是,对于城镇,我还需要另一个索引变量,例如 k 和循环。

public MultipartFile exportData() throws IOException {

    // code omitted for brevity

    int rowCount = 0;
    final List<CountryDTO> countryList = countryService.findAll();

    int iSize = countryList.size();
    for (int i = 0; i < iSize; i++) {
        int jSize = countryList.get(i).getCityList().size();
        for (int j = 0; j < jSize; j++) {
            int kSize = countryList.get(i).getCityList().get(j).getTownList().size();
            for (int j = 0; k < kSize; k++) {
                Row row = sheet.createRow(rowCount++);
                write(countryList.get(i), row, j, k);
            }
        }
    }

    // code omitted for brevity
}

private static void write(CountryDTO country, Row row, int j) {

    Cell cell = row.createCell(0);
    cell.setCellValue(country.getName());

    cell = row.createCell(1);
    cell.setCellValue(country.getCityList().get(j).getName());

    cell = row.createCell(2);
    cell.setCellValue(country.getCityList().get(j).getTownList().get(k).getName());
}

我不确定是否有更好的方法。由于我是使用 Java 生成报告的新手,我不知道如何继续使用以下方法(如果可以,我将使用这种方法,因为它已经在当前项目中使用过)。

【问题讨论】:

    标签: java report export-to-csv reporting export-to-excel


    【解决方案1】:

    对于每个

    您可以使用 for-each 语法而不是索引 for 循环。

    for( Country country : countryService.findAll() )
    {
        for( City city : country.getCityList() )
        {
            for( Town town : city.getTownList() )
            {
                write( country , city , town ) ;
            }
        }
    }
    

    请注意,我们重新定义了write 方法以忽略原始数据结构。它的工作是写入数据,而不是检索数据。不需要那种方法来理解嵌套列表。

    研究Separation Of Concerns。一个方法和一个类应该尽可能少地了解外部世界。这可以防止您的代码变成“brittle”,在这种情况下,一点点更改都会导致您的代码到处乱码。

    记录

    我会在 Java 16+ 中更进一步,将 record 对象传递给 write 方法。记录是编写一个类的简要方法,其主要目的是透明和不可变地传递数据。编译器隐式创建构造函数、getter、equals & hashCodetoString

    record CountryCityTown( String country , String city , String town ) {}
    

    更改write 方法以获取该类型的单个对象。

    void write ( CountryCityTown countryCityTown ) { … }
    

    【讨论】:

    猜你喜欢
    • 2019-04-09
    • 1970-01-01
    • 2021-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-21
    • 2019-08-04
    • 2015-10-25
    相关资源
    最近更新 更多