简体   繁体   English

Android - 从表值生成 CSV 文件

[英]Android - Generate CSV file from table values

I have a database containing one table, i want to generate CSV file with values of this table.我有一个包含一个表的数据库,我想用这个表的值生成 CSV 文件。

Actually, I want to email this CSV file as an attachment.实际上,我想将此 CSV 文件作为附件通过电子邮件发送。 I know about sending file as an attachment in email intent(ACTION_SEND) , but I don't know the procedure of creating or the method by which i can create CSV formatted file.我知道在电子邮件intent(ACTION_SEND)中将文件作为附件发送,但我不知道创建过程或创建 CSV 格式文件的方法。

Please give me suggestions or ideas.请给我建议或想法。

You can use opencsv for this您可以为此使用opencsv

Download the library from here:从这里下载库:

http://sourceforge.net/projects/opencsv/ http://sourceforge.net/projects/opencsv/

In this you can find jar file.在这里你可以找到 jar 文件。

Inside your activity use this:在你的活动中使用这个:

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
}

THis might be helpfull.I needed ';'这可能会有所帮助。我需要';' as seperator in between the feild values.作为字段值之间的分隔符。 Please use ',' accordingly for CSV generation.请相应地使用“,”来生成 CSV。

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

    }






}

This looks really promising.这看起来很有希望。 It will take any Java object and convert it to a CSV file:它将获取任何 Java 对象并将其转换为 CSV 文件:

http://supercsv.sourceforge.net/ http://supercsv.sourceforge.net/

It also might be possible to retrieve the data from the database in CSV format.也可以从数据库中以 CSV 格式检索数据。

Adding to @Cocos2dx answer:添加到@Cocos2dx 答案:

When querying from db you may have null fields, in my case i use a Controller to fetch the data in an object list, but either if you don`t you should check for null or empty values and proper format them (or they can make your table look weird):从数据库查询时,您可能有空字段,在我的情况下,我使用控制器来获取对象列表中的数据,但是如果您不这样做,您应该检查空值或空值并正确格式化它们(或者它们可以使你的桌子看起来很奇怪):

String[] details = { 
        replaceNull(someObject.getId()),
        replaceNull(someObject.getName())
};


public static String replaceNull(String input) {
    return ((input == null || input.isEmpty()) ? " " : input);
}

writer.writeNext(details);

In case of using Kotlin, I recommend kotlin-csv library.如果使用 Kotlin,我推荐kotlin-csv库。

Just get the list of DB table objects, go through all of them and add the column values to CSV rows, one by one, like this:只需获取 DB 表对象的列表,遍历所有对象并将列值一一添加到 CSV 行,如下所示:

csvWriter().open(csvFile) {
    // Header
    writeRow(listOf("[id]", "[name]", "[age]"))

    peopleList.forEachIndexed { index, person ->
        writeRow(listOf(index, person.fullName, person.age))
    }
}

I explain the whole process of creating csv file here .我在这里解释了创建 csv 文件的整个过程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM