您的位置:首页 > 移动开发 > Android开发

Android将SQLite数据表导出到csv格式文件 .

2013-01-07 17:11 701 查看
/article/8340113.html

通过FileWriter和BufferedWriter将SQLite数据表导出到csv格式文件的简单方法如下:

[java]
view plaincopyprint?

public void ExportToCSV(Cursor c, String fileName) {

int rowCount = 0;
int colCount = 0;
FileWriter fw;
BufferedWriter bfw;
File sdCardDir = Environment.getExternalStorageDirectory();
File saveFile = new File(sdCardDir, fileName);
try {

rowCount = c.getCount();
colCount = c.getColumnCount();
fw = new FileWriter(saveFile);
bfw = new BufferedWriter(fw);
if (rowCount > 0) {
c.moveToFirst();
// 写入表头

for (int i = 0; i < colCount; i++) {
if (i != colCount - 1)
bfw.write(c.getColumnName(i) + ',');
else
bfw.write(c.getColumnName(i));
}
// 写好表头后换行
bfw.newLine();
// 写入数据
for (int i = 0; i < rowCount; i++) {
c.moveToPosition(i);
// Toast.makeText(mContext, "正在导出第"+(i+1)+"条",

// Toast.LENGTH_SHORT).show();

Log.v("导出数据", "正在导出第" + (i + 1) + "条");
for (int j = 0; j < colCount; j++) {
if (j != colCount - 1)
bfw.write(c.getString(j) + ',');
else
bfw.write(c.getString(j));
}
// 写好每条记录后换行
bfw.newLine();
}
}
// 将缓存数据写入文件
bfw.flush();
// 释放缓存
bfw.close();
// Toast.makeText(mContext, "导出完毕!", Toast.LENGTH_SHORT).show();

Log.v("导出数据", "导出完毕!");
} catch (IOException e) {
// TODO Auto-generated catch block

e.printStackTrace();
} finally {
c.close();
}
}

public void ExportToCSV(Cursor c, String fileName) {

int rowCount = 0;
int colCount = 0;
FileWriter fw;
BufferedWriter bfw;
File sdCardDir = Environment.getExternalStorageDirectory();
File saveFile = new File(sdCardDir, fileName);
try {

rowCount = c.getCount();
colCount = c.getColumnCount();
fw = new FileWriter(saveFile);
bfw = new BufferedWriter(fw);
if (rowCount > 0) {
c.moveToFirst();
// 写入表头
for (int i = 0; i < colCount; i++) {
if (i != colCount - 1)
bfw.write(c.getColumnName(i) + ',');
else
bfw.write(c.getColumnName(i));
}
// 写好表头后换行
bfw.newLine();
// 写入数据
for (int i = 0; i < rowCount; i++) {
c.moveToPosition(i);
// Toast.makeText(mContext, "正在导出第"+(i+1)+"条",
// Toast.LENGTH_SHORT).show();
Log.v("导出数据", "正在导出第" + (i + 1) + "条");
for (int j = 0; j < colCount; j++) {
if (j != colCount - 1)
bfw.write(c.getString(j) + ',');
else
bfw.write(c.getString(j));
}
// 写好每条记录后换行
bfw.newLine();
}
}
// 将缓存数据写入文件
bfw.flush();
// 释放缓存
bfw.close();
// Toast.makeText(mContext, "导出完毕!", Toast.LENGTH_SHORT).show();
Log.v("导出数据", "导出完毕!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
c.close();
}
}

调用方法:

[java]
view plaincopyprint?

Cursor c = helper.rawQuery("select * from test", null); ExportToCSV(c, "test.csv");

Cursor c = helper.rawQuery("select * from test", null);
ExportToCSV(c, "test.csv");
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: