How to export data to csv file in Android?

被刻印的时光 ゝ 提交于 2019-11-28 22:24:56

问题


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:


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();


来源:https://stackoverflow.com/questions/27772011/how-to-export-data-to-csv-file-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!