Exporting data to a CSV file
Sometimes, it's more convenient to view data using a spreadsheet program such as LibreOffice, Microsoft Office Excel, or Apple Numbers. A standard way to export and import simple spreadsheet tables is through Comma Separated Values (CSVs).
In this recipe, we will use the cassava
package to easily encode a CSV file out of a data structure.
Getting ready
Install the Cassava CSV package from cabal, using the following command line:
$ cabal install cassava
How to do it…
- Import the relevant packages using the following code:
import Data.Csv import qualified Data.ByteString.Lazy as BSL
- Define an association list of data that will be exported as CSV. For this recipe, we will pair letters and numbers together, as shown in the following code:
myData :: [(Char, Int)] myData = zip ['A'..'Z'] [1..]
- Run the
encode
function to convert the data structure into a lazy ByteString CSV representation, as shown in the following code:main = BSL.writeFile "...