如何使用 vaadin 网格导出到 csv/excel?

2024-04-07

在 Vaadin 14+ 中,我正在创建网格,并希望用户有一种稳定/简单的方法将网格内容导出到 csv 或最好是 Excel。为此,我很惊讶 Vaadin 似乎没有提供此功能,因此必须使用第 3 方开发人员插件(例如https://vaadin.com/directory/component/exporter/overview https://vaadin.com/directory/component/exporter/overview)。然而,这些插件有许多错误(例如,无法将带有日期值的网格正确导出到 Excel 等)。 Vaadin 14 中是否有推荐的方法来支持我认为是任何基于 Web 的网格小部件的强烈要求的功能?


不需要插件(称为add-ons在瓦丁)。

DataProvider

你需要明白Grid https://vaadin.com/api/platform/14.1.18/com/vaadin/flow/component/grid/Grid.html小部件是为了推介会,而不是数据存储。

Each Grid对象由一个支持DataProvider https://vaadin.com/api/platform/14.1.18/com/vaadin/flow/data/provider/DataProvider.html,它负责访问数据存储。要显示的数据在Grid可能来自内存中的某些对象,或者来自数据源,或者来自数据库查询的结果,或者来自某些其他源。遵循以下设计原则关注点分离 https://en.wikipedia.org/wiki/Separation_of_concerns, the Grid类只关心显示数据,而不是管理数据访问。这DataProvider界面涉及管理数据访问,而不是显示数据。所以Grid and DataProvider一起工作。

对于基于内存的有限数量的数据对象,我们可以使用ListDataProvider https://vaadin.com/api/platform/14.1.18/com/vaadin/flow/data/provider/ListDataProvider.html实施DataProvider。当我们传递数据对象的集合时,可以自动为我们构建此列表数据提供程序。

所以你不要从Grid目的。相反,您想监听DataProvider,然后提供导出通过该数据提供商获得的数据。

没有内置的导出功能DataProvider。您可以编写自己的导出功能,同时利用 中提供的数据DataProvider执行。您可以在许多基于 Java 的库中进行选择,以帮助为导出的数据编写数据文件。在下面所示的代码中,我们使用Apache 共享 CSV用于编写制表符分隔或逗号分隔值的库。

这是一个完整的示例应用程序。

我们有一个简单的Person类来保存姓名和电话号码。

package work.basil.example;

import java.util.Objects;

public class Person
{
    //---------------|  Member vars  |--------------------------------
    private String name, phone;


    //---------------|  Constructors  |--------------------------------

    public Person ( String name , String phone )
    {
        this.name = name;
        this.phone = phone;
    }


    //---------------|  Accessors  |--------------------------------

    public String getName ( ) { return this.name; }

    public void setName ( String name ) { this.name = name; }

    public String getPhone ( ) { return this.phone; }

    public void setPhone ( String phone ) { this.phone = phone; }


    //---------------|  Object  |--------------------------------


    @Override
    public boolean equals ( Object o )
    {
        if ( this == o ) return true;
        if ( o == null || getClass() != o.getClass() ) return false;
        Person person = ( Person ) o;
        return getName().equals( person.getName() );
    }

    @Override
    public int hashCode ( )
    {
        return Objects.hash( getName() );
    }
}

这是一个完整的 Vaadin 14.1.18 应用程序,生成 4Person对象作为样本数据集。这些对象被馈送到Grid,这会产生一个ListDataProvider为了我们的方便。

我们有一个文本字段用于编辑所选电话号码Person网格中表示的对象。

我们有一个导出按钮,它使用Apache 共享 CSV http://commons.apache.org/proper/commons-csv/库写出一个CSV https://en.wikipedia.org/wiki/Comma-separated_values文件。请注意我们从以下位置访问数据项的关键行:ListDataProvider。首先我们将数据提供者转换为ListDataProvider,然后我们提取一个Collection所有的Person里面存储的对象。Java 泛型 https://en.wikipedia.org/wiki/Generics_in_Java提供类型安全,并使编译器能够知道数据提供者包含Person对象。

Collection < Person > persons = ( ( ListDataProvider < Person > ) grid.getDataProvider() ).getItems();

完整的 Vaadin 14.1 应用程序代码如下。

package work.basil.example;

import com.vaadin.flow.component.AbstractField;
import com.vaadin.flow.component.ClickEvent;
import com.vaadin.flow.component.Key;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.button.ButtonVariant;
import com.vaadin.flow.component.dependency.CssImport;
import com.vaadin.flow.component.dialog.Dialog;
import com.vaadin.flow.component.grid.Grid;
import com.vaadin.flow.component.grid.GridSingleSelectionModel;
import com.vaadin.flow.component.html.Input;
import com.vaadin.flow.component.notification.Notification;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.data.provider.ListDataProvider;
import com.vaadin.flow.router.Route;
import com.vaadin.flow.server.PWA;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;

import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Optional;

/**
 * The main view contains a button and a click listener.
 */
@Route ( "" )
//@PWA ( name = "Project Base for Vaadin", shortName = "Project Base" )
@CssImport ( "./styles/shared-styles.css" )
@CssImport ( value = "./styles/vaadin-text-field-styles.css", themeFor = "vaadin-text-field" )
public class MainView extends VerticalLayout
{

    Grid < Person > grid;
    TextField phoneField;
    Button phoneSaveButton, exportButton;

    public MainView ( )
    {
        // Widgets
        List < Person > personList = new ArrayList <>( 4 );
        personList.add( new Person( "Alice" , "555.123.1234" ) );
        personList.add( new Person( "Bob" , "555.688.4787" ) );
        personList.add( new Person( "Carol" , "555.632.2664" ) );
        personList.add( new Person( "David" , "555.543.2323" ) );

        // Create a grid bound to the list
        grid = new Grid <>();
        grid.setItems( personList );
        grid.addColumn( Person :: getName ).setHeader( "Name" );
        grid.addColumn( Person :: getPhone ).setHeader( "Phone" );
        GridSingleSelectionModel < Person > singleSelect = ( GridSingleSelectionModel < Person > ) grid.getSelectionModel();
        singleSelect.setDeselectAllowed( false );
        singleSelect.addSingleSelectionListener( singleSelectionEvent -> {
                    Optional < Person > personOptional = singleSelectionEvent.getSelectedItem();
                    if ( personOptional.isPresent() )
                    {
                        this.phoneField.setValue( personOptional.get().getPhone() );
                    }
                }
        );

        phoneField = new TextField( "Phone:" );

        phoneSaveButton = new Button( "Update phone on person " );
        phoneSaveButton.addClickListener(
                ( ClickEvent < Button > clickEvent ) -> {
                    Optional < Person > personOptional = ( ( GridSingleSelectionModel < Person > ) grid.getSelectionModel() ).getSelectedItem();
                    if ( personOptional.isEmpty() )
                    {
                        Notification.show( "First, select a person in list." );
                    } else
                    {
                        Person person = personOptional.get();
                        person.setPhone( phoneField.getValue() );
                        grid.getDataProvider().refreshItem( person );
                    }
                }
        );

        exportButton = new Button( "Export" );
        exportButton.setEnabled( false );
        exportButton.addClickListener(
                ( ClickEvent < Button > clickEvent ) -> {
                    String fileName = "Persons_" + Instant.now().toString() + ".csv";
                    final String fileNamePath = "/Users/basilbourque/" + fileName;
                    try (
                            BufferedWriter writer = Files.newBufferedWriter( Paths.get( fileNamePath ) ) ;
                            CSVPrinter csvPrinter = new CSVPrinter( writer , CSVFormat.RFC4180.withHeader( "Name" , "Phone" ) ) ;
                    )
                    {
                        Collection < Person > persons = ( ( ListDataProvider < Person > ) grid.getDataProvider() ).getItems();
                        for ( Person person : persons )
                        {
                            csvPrinter.printRecord( person.getName() , person.getPhone() );
                        }
                    }
                    catch ( IOException e )
                    {
                        e.printStackTrace();
                    }

                    // Tell user.
                    Notification.show( "Exported to file in your home folder: " + fileName );
                }
        );
        grid.getDataProvider().addDataProviderListener( dataChangeEvent -> {
            exportButton.setEnabled( true );
        } );


        // Arrange
        this.add( grid , phoneField , phoneSaveButton , exportButton );
    }
}

顺便说一下,Apache Commons CSV 提供了多种文件格式。通常,最好的格式是 RFC 4180 中定义的标准格式。但是您提到了 Microsoft Excel,该库支持该变体。请参阅CSVFormat https://commons.apache.org/proper/commons-csv/apidocs/index.html class.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 vaadin 网格导出到 csv/excel? 的相关文章

随机推荐