我有一个包含一个表格的数据库,想要生成CSV文件并将表格中的值导入其中。
实际上,我希望将这个CSV文件作为附件发送邮件。我知道通过intent(ACTION_SEND)
在邮件中以附件形式发送文件,但我不知道如何创建CSV格式的文件或者可以使用哪种方法创建。
请给我一些建议或想法。
opencsv
实现此功能。CSVWriter writer = null;
try
{
writer = new CSVWriter(new FileWriter("/sdcard/myfile.csv"), ',');
String[] entries = "first#second#third".split("#"); // array of your values
writer.writeNext(entries);
writer.close();
}
catch (IOException e)
{
//error
}
这可能会有所帮助。在字段值之间,我需要使用';'作为分隔符。请相应地使用','进行CSV生成。
谢谢, Darshan
private void exportTheDB() throws IOException
{
File myFile;
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");
String TimeStampDB = sdf.format(cal.getTime());
try {
myFile = new File(extStorageDirectory+"/Export_"+TimeStampDB+".csv");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append("Start time;End time;Elapse;Sports type");
myOutWriter.append("\n");
sampleDB = this.openOrCreateDatabase(DB_NAME,MODE_PRIVATE, null);
Cursor c = sampleDB.rawQuery("SELECT * FROM Sport_Records ", null);
if (c != null) {
if (c.moveToFirst()) {
do {
String start_Time = c.getString(c.getColumnIndex("startTimeDate"));
String end_Time = c.getString(c.getColumnIndex("endTimeDate"));
String elapse_Time = calculateTimeDifferece(end_Time, start_Time);
String sport_Name = c.getString(c.getColumnIndex("label"));
myOutWriter.append(start_Time+";"+end_Time+";"+elapse_Time+";"+sport_Name);
myOutWriter.append("\n");
}
while (c.moveToNext());
}
c.close();
myOutWriter.close();
fOut.close();
}
} catch (SQLiteException se)
{
Log.e(getClass().getSimpleName(),"Could not create or Open the database");
}
finally {
sampleDB.close();
}
}
String[] details = {
replaceNull(someObject.getId()),
replaceNull(someObject.getName())
};
public static String replaceNull(String input) {
return ((input == null || input.isEmpty()) ? " " : input);
}
writer.writeNext(details);
csvWriter().open(csvFile) {
// Header
writeRow(listOf("[id]", "[name]", "[age]"))
peopleList.forEachIndexed { index, person ->
writeRow(listOf(index, person.fullName, person.age))
}
}
我在这里解释了创建CSV文件的整个过程。
close()
的情况下它不会被保存。 - Tina J