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

通过FileWriter和BufferedWriter将SQLite数据表导出到csv格式文件的简单方法如下:
[java]  view plain copy
  1. public void ExportToCSV(Cursor c, String fileName) {  
  2.   
  3.         int rowCount = 0;  
  4.         int colCount = 0;  
  5.         FileWriter fw;  
  6.         BufferedWriter bfw;  
  7.         File sdCardDir = Environment.getExternalStorageDirectory();  
  8.         File saveFile = new File(sdCardDir, fileName);  
  9.         try {  
  10.   
  11.             rowCount = c.getCount();  
  12.             colCount = c.getColumnCount();  
  13.             fw = new FileWriter(saveFile);  
  14.             bfw = new BufferedWriter(fw);  
  15.             if (rowCount > 0) {  
  16.                 c.moveToFirst();  
  17.                 // 写入表头  
  18.                 for (int i = 0; i < colCount; i++) {  
  19.                     if (i != colCount - 1)  
  20.                        bfw.write(c.getColumnName(i) + ',');  
  21.                     else  
  22.                        bfw.write(c.getColumnName(i));  
  23.                 }  
  24.                 // 写好表头后换行  
  25.                 bfw.newLine();  
  26.                 // 写入数据  
  27.                 for (int i = 0; i < rowCount; i++) {  
  28.                     c.moveToPosition(i);  
  29.                     // Toast.makeText(mContext, "正在导出第"+(i+1)+"条",  
  30.                     // Toast.LENGTH_SHORT).show();  
  31.                     Log.v("导出数据""正在导出第" + (i + 1) + "条");  
  32.                     for (int j = 0; j < colCount; j++) {  
  33.                         if (j != colCount - 1)  
  34.                             bfw.write(c.getString(j) + ',');  
  35.                         else  
  36.                            bfw.write(c.getString(j));  
  37.                     }  
  38.                     // 写好每条记录后换行  
  39.                     bfw.newLine();  
  40.                 }  
  41.             }  
  42.             // 将缓存数据写入文件  
  43.             bfw.flush();  
  44.             // 释放缓存  
  45.             bfw.close();  
  46.             // Toast.makeText(mContext, "导出完毕!", Toast.LENGTH_SHORT).show();  
  47.             Log.v("导出数据""导出完毕!");  
  48.         } catch (IOException e) {  
  49.             // TODO Auto-generated catch block  
  50.             e.printStackTrace();  
  51.         } finally {  
  52.             c.close();  
  53.         }  
  54.     }  
调用方法:
[java]  view plain copy
  1. Cursor c = helper.rawQuery("select * from test"null);  
  2. ExportToCSV(c, "test.csv");  

你可能感兴趣的:(Android将SQLite数据表导出到csv格式文件)