【问题标题】:In Android how to append a new line to .CSV file with a Cursor在 Android 中如何使用光标将新行附加到 .CSV 文件
【发布时间】:2015-12-24 01:22:19
【问题描述】:

我已经为此工作了很长一段时间,我能得到的最远的结果就是将整个查询从 DB 写入 .CSV 文件中的一行。

当我将 writeNext(string[]) 与 .csv 下面的代码一起使用时,会写在一条长线上。

//Export the orders in the database to a CSV file.  Can be transferred from device either by USB or bluetooth
public void exportOrders(View view)
{
    try
    {
        CSVWriter writer;
        writer = new CSVWriter(new FileWriter("/sdcard/orders.csv"), ',');
        writer.writeNext(cursor.getColumnNames()); //Write the column headings first before the looping starts
        //Loop through all results (use row count of table)
        for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext())
        {
            String[] entries = (cursor.getString(0)+ "," +cursor.getString(1)+ "," +cursor.getString(2)+ "," +cursor.getString(3)
                    + "," +cursor.getString(4)).split(","); //Split the string by the delimiter
            writer.writeNext(entries); //Write current row of DB to file
            writer.flush(); //Flush the stream
        }
        Toast.makeText(this, "Orders exported to .CSV successfully!", Toast.LENGTH_SHORT).show();
        writer.close();
    }
    catch (Exception erMsg)
    {
        Toast.makeText(this, erMsg.toString(), Toast.LENGTH_LONG).show();
        erMsg.printStackTrace();
    }
}

从我正在阅读的内容来看,这似乎是这样做的方法,但我看不出如何从该代码生成新行?有没有办法将光标与新行一起使用,或者使用 ResultSet 和 writeAll(result) 是标准的吗?

【问题讨论】:

    标签: android csv cursor newline resultset


    【解决方案1】:

    这样做的解决方案是使用正确的参数声明 CSVWriter。这是新的构造函数:

    writer = new CSVWriter(new FileWriter("/sdcard/orders.csv"), ',',  CSVWriter.NO_QUOTE_CHARACTER, CSVWriter.DEFAULT_ESCAPE_CHARACTER, "\r\n");
    

    这将允许为每一行创建一个新行。为确保此方法有效,请使用 "\r\n" 而不仅仅是 "\n",因为某些编辑器无法识别 "\n"强>。

    【讨论】:

      猜你喜欢
      • 2018-05-24
      • 2017-07-28
      • 2014-01-27
      • 2018-05-16
      • 1970-01-01
      • 2019-01-09
      • 2019-03-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多