cancel
Showing results for 
Search instead for 
Did you mean: 
Read only

How to export results of flexible search query to a csv file using groovy script

tescopolitan
Explorer
0 Likes
6,815

I have a flexible search query which involves joins and want to export the results of this query into a csv file. The impex export process doesn't seem to work because of the joins. Anyone know of a groovy script I can use to export the results of the query to a csv file?

Accepted Solutions (0)

Answers (1)

Answers (1)

It's possible to write a CSV file via Groovy but in my opinion ImpEx would be the right choice here.

Anyways here's some ugly code I quickly put together to get you started. I'm using apache-commons-csv in this example and I'd always recommend using a proven csv library like this one instead of writing the CSV file manually since you'd probably run into escaping issues, not handle multiline values properly and so on.

Happy refactoring.

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.io.FileUtils;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.io.File;

final String targetFile = "/Users/what-ever/Desktop/TEST.CSV";

final File file = new File(targetFile);

byte[] bom = [0xEF, 0xBB, 0xBF]; // small "hack" to make this work with Microsoft Excel
FileUtils.writeByteArrayToFile(file, bom, false);

final Writer writer = new OutputStreamWriter(FileUtils.openOutputStream(file, true), "UTF-8");
final CSVPrinter printer = CSVFormat.DEFAULT.withHeader("Code", "Field 1", "Field 2").withDelimiter((char)';').print(writer);

def flexibleSearchService = spring.getBean("flexibleSearchService");
def result = flexibleSearchService.search("SELECT {PK} FROM {Product}").getResult()

for(def product : result) {
  printer.printRecord(product.getCode(), product.getField1(), product.getField2());
}


printer.close();
tescopolitan
Explorer
0 Likes

CSVFormat and CSVPrinter are invalid in our environment.

0 Likes

Then you might need to add the dependency to your project or use a different CSV writer such as the one that comes with hybris (de.hybris.platform.util.CSVWriter).