Importing Data from a CSV
There are several ways to import data from a CSV file. First, we could use system.file.readFileAsString to read the entire file as a string. Note, that this will read the file as is, meaning "
\n" can be used to denote new lines.
Alternatively, Python's CSV Library could be use to read in the contents of a CSV. In some cases, this is the easier approach, as the reader object is ready to be iterated over. Note, that this approach does read in each row as a List of strings:
Converting the Data into a Dataset
Once you've read in the contents of a CSV into a script, you may wish to move it elsewhere. It is not uncommon to move the data to a Power Table, or other components on the screen. The main difficulty with this is converting the CSV data into a dataset so that it fits into the Power Table component's Data property. We have a couple of approaches listed below.
Calling the system.dataset.fromCSV Function
The system.dataset.fromCSV function can take a string and convert it to a dataset. Note, that the function expects a very specific format:
- Create a Text file on your local system named "example.csv."
- Open the Text file, copy the contents of the "CSV file Content" box above, and paste the contents to the file. Save the changes to the example.csv file.
Let's move the contents of a CSV file to a Power Table. Add a Power Table and a Button component to your window. Double click on the Button component, and paste the following code into the Script Editor of the actionPerformed event:
- To execute your script, put the Designer into Preview Mode, and press the Button. A window will open for you for you to navigate and choose your CSV file, then click Open.
- Your data will be displayed in the Power Table as shown below.
Calling the csv.reader Function
As mentioned, system.dataset.fromCSV() requires a specific format, which may not match the format of your file. In this case, we can use Python's CSV Library to parse the file and convert it to a dataset.
Here is the code to import the above CSV data.