Skip to content

Instantly share code, notes, and snippets.

@old-repo-ekoteguh
Created March 28, 2014 02:48
Show Gist options
  • Save old-repo-ekoteguh/9824184 to your computer and use it in GitHub Desktop.
Save old-repo-ekoteguh/9824184 to your computer and use it in GitHub Desktop.
Here is example of converting data ArrayList<Properties> to CSV in Java programming. I use library OpenCSV to convert this data.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package contoh.manipulasi.csv;
import au.com.bytecode.opencsv.CSVWriter;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Properties;
/**
*
* @author Eko Teguh Widodo
*/
public class ConvertDataToCSV {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws Exception {
// TODO code application logic here
ArrayList<Properties> arrs = new ArrayList<Properties>();
// Kode ini saya gunakan untuk memasukkan data ke dalam bentuk ArrayList<Properties>
// Kerena biasanya, data yang ada dalam database bentuknya seperti tipe di atas.
String[][] mahasiswa = {{"08.001","Adi Achmad","Jawa Tengah"},{"08.002","Budi Budiman","Jakarta"},{"08.003","Cita Citra","Bandung"}};
for (String[] s: mahasiswa){
Properties prop = new Properties();
prop.put("nim",s[0]);
prop.put("nama",s[1]);
prop.put("asal",s[2]);
arrs.add(prop);
}
// Untuk melihat data dalam bentuk ArrayList<Properties>
System.out.println(arrs);
// Mulai melakukan konversi data di atas dalam bentuk CSV dengan ekstensi .ku dan pemisahnya adalah tanda pagar (#)
CSVWriter writer = new CSVWriter(new FileWriter("mahasiswa.ku"), '#');
// Berikan header dulu
String[] header = "nim#nama#asal".split("#");
writer.writeNext(header);
for(Properties p: arrs){
String[] cells = (p.getProperty("nim")+"#"+p.getProperty("nama")+"#"+p.getProperty("asal")).split("#");
writer.writeNext(cells);
}
writer.close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment