Android - 根据表值生成CSV文件
问题描述:
我有一个包含一个表的数据库,我想用这个表的值生成CSV文件。Android - 根据表值生成CSV文件
实际上,我想通过电子邮件发送该CSV文件作为附件。我知道发送文件作为附件在电子邮件intent(ACTION_SEND)
,但我不知道创建过程或我可以创建CSV格式的文件的方法。
请给我一些建议或想法。
答
您可以使用opencsv
这个
下载库从这里:
http://sourceforge.net/projects/opencsv/
在这你可以找到jar文件。
内,您的活动中使用这样的:
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
}
答
,这可能是helpfull.I需要 ';'作为场地价值之间的分离者。请使用','来生成CSV。
感谢, 达山
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();
}
}
答
添加到@ Cocos2dx答案:
当从DB你可能有空字段查询,在我来说,我通过一个控制器对象获取数据但是要么你不应该检查空值或空值并正确格式化它们(或者它们可以使你的表看起来很奇怪):
String[] details = {
replaceNull(someObject.getId()),
replaceNull(someObject.getName())
};
public static String replaceNull(String input) {
return ((input == null || input.isEmpty()) ? " " : input);
}
writer.writeNext(details);
我有访问了你提供的链接,但我没有来知道我如何在我的android应用程序中包含这个。请让我知道,Thanx为您的快速响应 – 2011-01-08 06:19:03
我认为你的意思是我应该包括这个CSVWriter类,然后我应该玩这个CSVWriter类,是这样吗? – 2011-01-08 06:25:35