In addition to searching, two common features implemented in DataGrids are import/export and copy/paste. There are a number of great solutions already out there. The purpose of this post is to show how we can bring them together (along with some additional code/tweaks) to provide the user with a DataGrid which plays nicely with their favorite spreadsheet application.
Overview of demo
- There are three ways to copy the selected items from the left DataGrid: using the “Copy” button, pressing Ctrl+C or right clicking and then selecting “Copy Item(s)”.
- The copied data is stored in tab separated format, when pasting it into a spreadsheet it will retain its column structure.
- To paste data into the right DataGrid give it the focus by clicking on it and then press Ctrl+V.
- Click “Import” to upload either a CSV (comma sperated) or TSV (tab separated) file.
- Click “Export” to generate a CSV file of the data in the DataGrid.
In Flex 3, in order to upload a file you need a small script on the server (in Flex 4/Flash 10 the client is able to handle this locally). Included in the source you’ll find two PHP files: csvImport.php and csvExport.php. To support exporting the data from the DataGrid I’m leveraging a nice algorithm written by Sasa Radovanovic explained in this post.
This solution is meant to work with plain text csv and tsv files, if you need to support Excel (.xls) files I’d recommend checking out as3xls.
One of the limitations of the Flash Player is that (for security reasons) we’re unable to access data from the user’s clipboard. This makes pasting rather tricky. Manish Jethani has documented a clever solution in this post where he uses a hidden text field to allow the user to paste data into a DataGrid.
This component provides the user with a way to map the columns in the data to the properties of the objects. It will attempt to determine if the first row of the data looks like it should be a header row and will then try to automatically map the fields.
Hope you find this useful,