on ‎2020 Sep 14 7:55 PM
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?
Request clarification before answering.
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();
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
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).
| User | Count |
|---|---|
| 1 | |
| 1 | |
| 1 | |
| 1 | |
| 1 | |
| 1 | |
| 1 | |
| 1 |
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.