import ballerina/io;

public function main() returns error? {
    // Initializes the CSV file path and content.
    string csvFilePath1 = "./files/csvFile1.csv";
    string csvFilePath2 = "./files/csvFile2.csv";
    string[][] csvContent = [["1", "James", "10000"], ["2", "Nathan", "150000"],
    ["3", "Ronald", "120000"], ["4", "Roy", "6000"],
    ["5", "Oliver", "1100000"]];

    // Writes the given content string[][] to a CSV file.
    check io:fileWriteCsv(csvFilePath1, csvContent);
    // If the write operation was successful, then, performs a read operation to read the CSV content as a string array of arrays.
    string[][] readCsv = check io:fileReadCsv(csvFilePath1);
    io:println(readCsv);

    // Writes the given content stream to a CSV file.
    check io:fileWriteCsvFromStream(csvFilePath2, csvContent.toStream());
    // If the write operation was successful, then, perform a read operation to read the CSV content as a stream.
    stream<string[], io:Error?> csvStream = check
                                        io:fileReadCsvAsStream(csvFilePath2);
    // Iterates through the stream and prints the content.
    error? e = csvStream.forEach(function(string[] val) {
                              io:println(val);
                          });
}

Read/Write CSV

This sample demonstrates how to read/write from/to a CSV file using the CSV channel of the I/O API.

For more information on the underlying module, see the IO module.

import ballerina/io;
public function main() returns error? {
    string csvFilePath1 = "./files/csvFile1.csv";
    string csvFilePath2 = "./files/csvFile2.csv";
    string[][] csvContent = [["1", "James", "10000"], ["2", "Nathan", "150000"],
    ["3", "Ronald", "120000"], ["4", "Roy", "6000"],
    ["5", "Oliver", "1100000"]];

Initializes the CSV file path and content.

    check io:fileWriteCsv(csvFilePath1, csvContent);

Writes the given content string[][] to a CSV file.

    string[][] readCsv = check io:fileReadCsv(csvFilePath1);
    io:println(readCsv);

If the write operation was successful, then, performs a read operation to read the CSV content as a string array of arrays.

    check io:fileWriteCsvFromStream(csvFilePath2, csvContent.toStream());

Writes the given content stream to a CSV file.

    stream<string[], io:Error?> csvStream = check
                                        io:fileReadCsvAsStream(csvFilePath2);

If the write operation was successful, then, perform a read operation to read the CSV content as a stream.

    error? e = csvStream.forEach(function(string[] val) {
                              io:println(val);
                          });
}

Iterates through the stream and prints the content.

bal run io_csv.bal
[["1","James","10000"],["2","Nathan","150000"],["3","Ronald","120000"],["4","Roy","6000"],["5","Oliver","1100000"]]
["1","James","10000"]
["2","Nathan","150000"]
["3","Ronald","120000"]
["4","Roy","6000"]
["5","Oliver","1100000"]