I wanted to do the same just a few days ago and came up with my own method to transform a given 2-dimensional array of Strings representing the content to be transformed into CSV. Database records are basically nothing else than such an array. Note that this method changes the supplied array instead of working on its own copy (call by reference).
Basically all you have to do is to quote existing quotes in the original cell and, if it contains the separator for CSV records (usually a semicolon or comma), to quote the whole cell as well.
Code:
public void formatData(String[][] source)
{
if (source != null)
{
int width = source.length;
for (int i = 0; i < width; i++)
{
int height = source[i].length;
int lastCol = height - 1;
for (int j = 0; j < height; j++)
{
String cell = source[i][j];
if (cell == null)
{
cell = EMPTY_STRING;
}
else
{
// quote existing quotes
cell = cell.replaceAll(QUOTE, QUOTE + QUOTE);
// quote cell data if it contains the separator
if (cell.contains(SEPARATOR))
{
cell = QUOTE + cell + QUOTE;
}
}
// add separator to cells that are not in the last column
if (j < lastCol)
{
cell += SEPARATOR;
}
source[i][j] = cell.trim();
}
}
}
}