在 Android 如何使用光标将新行附加到 .CSV 文件
In Android how to append a new line to .CSV file with a Cursor
我从事这项工作已经有一段时间了,我最多只能将整个查询从数据库写入一长行的 .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();
}
}
根据我的阅读,这似乎是实现它的方法,但我看不出如何从该代码生成新行?有没有办法在新行中使用 Cursor,或者使用 ResultSet 和 writeAll(result) 是标准的吗?
这样做的解决方案是使用正确的参数声明 CSVWriter。这是新的构造函数:
writer = new CSVWriter(new FileWriter("/sdcard/orders.csv"), ',', CSVWriter.NO_QUOTE_CHARACTER, CSVWriter.DEFAULT_ESCAPE_CHARACTER, "\r\n");
这将允许为每一行创建一个新行。为确保这有效,请使用 "\r\n" 而不是 "\n"" 因为有些编辑不认识 "\n".
我从事这项工作已经有一段时间了,我最多只能将整个查询从数据库写入一长行的 .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();
}
}
根据我的阅读,这似乎是实现它的方法,但我看不出如何从该代码生成新行?有没有办法在新行中使用 Cursor,或者使用 ResultSet 和 writeAll(result) 是标准的吗?
这样做的解决方案是使用正确的参数声明 CSVWriter。这是新的构造函数:
writer = new CSVWriter(new FileWriter("/sdcard/orders.csv"), ',', CSVWriter.NO_QUOTE_CHARACTER, CSVWriter.DEFAULT_ESCAPE_CHARACTER, "\r\n");
这将允许为每一行创建一个新行。为确保这有效,请使用 "\r\n" 而不是 "\n"" 因为有些编辑不认识 "\n".