How to export data to csv file in Android?

2019-03-10 04:32发布

I created a csv file with the following format which I'm aiming to output to the device's sd card:

Ship Name,Scientist Name,Scientist Email,Sample Volume,Sample Colour,Longitude,Latitude,Material,Date

Each of the vales in the csv will be of type string except for the last value of date. The name of the csv file is AnalysisData.csv

I've looked examples on Stackoverflow such as this, Export my data on CSV file from app android but this creates a new file which I don't want.

I have already added the opencsv jar to my project so just need a relevant example.

Does anyone have any advice on achieving this in Android?

1条回答
迷人小祖宗
2楼-- · 2019-03-10 05:10

Try with this code snippet :

String baseDir = android.os.Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = "AnalysisData.csv";
String filePath = baseDir + File.separator + fileName;
File f = new File(filePath );
CSVWriter writer; 
// File exist
if(f.exists() && !f.isDirectory()){
mFileWriter = new FileWriter(filePath , true);
writer = new CSVWriter(mFileWriter);
}
else {
writer = new CSVWriter(new FileWriter(filePath));
}
String[] data = {"Ship Name","Scientist Name", "...",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").formatter.format(date)});

writer.writeNext(data);

writer.close();
查看更多
登录 后发表回答