2015-07-13 8 views
-4

Мне нужно выгрузить все содержимое из таблицы в файл csv. Я немного искал Google и искал SO, чтобы найти ответ, но я не могу найти то, что ищу, вот что я нашел: Android - Generate CSV file from table values и http://howtodoinjava.com/2014/08/12/parse-read-write-csv-files-opencsv-tutorial/. Вот мой DB:Сбрасывание таблицы SQLite в файл CSV в Android Studio

public class DBhelper extends SQLiteOpenHelper { 

//TABLE COLUMNS 
private static final String[] COLUMNS = {DBhelper.ID, DBhelper.GIFTCARDS_NUMBER, DBhelper.GIFTCARDS_CREATED, 
     DBhelper.GIFTCARDS_CREATOR, DBhelper.GIFTCARDS_BALANCE}; 
private static final String ID = "_id"; 
private static final String GIFTCARDS_NUMBER = "number"; 
private static final String GIFTCARDS_CREATED = "created"; 
private static final String GIFTCARDS_CREATOR = "creator"; 
private static final String GIFTCARDS_BALANCE = "balance"; 

//DATABASE INFORMATION 
static final String DB_NAME = "GiftcardsDB"; 

//DATABSE VERSION 
static final int DB_VERSION = 1; 

// TABLE QUERY 
private static final String CREATE_TABLE = "CREATE TABLE giftcards (" + ID + 
     " INTEGER PRIMARY KEY AUTOINCREMENT, " + GIFTCARDS_NUMBER + " TEXT NOT NULL, " + GIFTCARDS_CREATED + 
     " TEXT NOT NULL, " + GIFTCARDS_CREATOR + " INTEGER NOT NULL, " + GIFTCARDS_BALANCE + " REAL);"; 

public DBhelper(Context context) { 
    super(context, DB_NAME, null, DB_VERSION); 

} 

@Override 
public void onCreate(SQLiteDatabase db) { 
    db.execSQL(CREATE_TABLE); 
} 

@Override 
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 
    db.execSQL("DROP TABLE IF EXISTS Giftcards"); 
    onCreate(db); 
}  

Я хотел бы некоторые пояснения относительно того, как делает CSVWriter и/или ResultSet работы. Заранее спасибо !

+2

Loop через ваши строки (добавление разделителя между значения столбцов) и добавьте их в текстовый файл. Сбросьте и закройте файл. –

+0

Значит, я использую только курсор, а не CSVWriter и ResultSet? Извините, я очень новичок в Android! –

+0

A Курсор ** является ** результатом, в том, что это набор строк. Я склонен использовать наименее возможные библиотеки сторонних разработчиков. Итак, да, я делаю это. –

ответ

1

полностью непроверенный, и немного грубо, но что-то вроде этого должно сделать трюк.

DatabaseHelper dbh = new DatabaseHelper(context); 
    SQLiteDatabase db = dbh.getReadableDatabase(); 
    Cursor cursor = db.rawQuery("SELECT * FROM giftcards",null); 
    FileOutputStream outputStream; 

    if(!cursor.moveToFirst()){ 
     // something went wrong - bad sql or no results 
    } 

    File file = new File(context.getFilesDir(), "output.csv"); 
    try { 
     outputStream = new FileOutputStream(file); 


     do{ 

      // if any of the columns have commas in their values, you will have to do more involved 
      // checking here to ensure they are escaped properly in the csv 

      // the numbes are column indexes. if you care about the order of the columns in your 
      // csv, you may want to move them around 

      outputStream.write(cursor.getString(0).getBytes()); 
      outputStream.write(",".getBytes()); 
      outputStream.write(cursor.getString(1).getBytes()); 
      outputStream.write(",".getBytes()); 
      outputStream.write(cursor.getString(2).getBytes()); 
      outputStream.write(",".getBytes()); 
      outputStream.write(cursor.getString(3).getBytes()); 
      outputStream.write(",".getBytes()); 
      outputStream.write(cursor.getString(4).getBytes()); 
      outputStream.write("\n".getBytes()); 


     } while(cursor.moveToNext()); 

     outputStream.flush(); 
     outputStream.close(); 

    } catch (Exception e){ 

     e.printStackTrace(); 
    } 


    cursor.close(); 
+0

Лучше промойте поток, прежде чем закрывать его. –

+1

Спасибо, что поймали это. Исправлена. – Zerp

0

Вот как я это сделал. Затем я сделал метод отправки файла csv по электронной почте.

public String createCSV(){ 

    boolean var = true; 
    File folder = new File(Environment.getExternalStorageDirectory() + "/Folder"); 
    if (!folder.exists()) 
     var = folder.mkdir(); 
    final String filename = folder.toString() + "/" + "Giftcards.csv"; 

    Uri u1 = null; 


    SQLiteDatabase db = this.getReadableDatabase(); 
    Cursor cursor = db.rawQuery("SELECT * FROM giftcards", null); 


    try { 
     FileWriter fw = new FileWriter(filename); 

     if (cursor != null) { 
      cursor.moveToFirst(); 
      for (int i = 0; i < cursor.getCount(); i++) { 
       for (int j = 0; j < cursor.getColumnNames().length; j++) { 
        fw.append(cursor.getString(j) + ";"); 
       } 
       fw.append("\n"); 

       cursor.moveToNext(); 
      } 
      cursor.close(); 
     } 
     fw.close(); 
    } catch(Exception e){ 
    } 
    return filename; 
} 
0

я думаю, что его слишком поздно, но это, как я это сделать, надеюсь, что это помогает другим, после концертирует в CSV-файл я отправить его через Bluetooth

SQLiteDatabase database = controller.getReadableDatabase(); 
      Cursor c = null; 
      try 
      { 
       c = database.rawQuery("Select * FROM Countsheet" , null); 
       int rowcount = 0; 
       int colcount = 0; 
       File sdCardDir = Environment.getExternalStorageDirectory(); 
       String filename = "/Physical Count.csv"; 
       File saveFile = new File(sdCardDir,filename); 
       FileWriter fileWriter = new FileWriter(saveFile); 

       BufferedWriter bw = new BufferedWriter(fileWriter); 
       rowcount = c.getCount(); 
       colcount = c.getColumnCount(); 

       if (rowcount > 0) 
        c.moveToFirst(); 
       for (int i = 0 ; i < colcount; i++) 
       { 
        if (i != colcount -1){ 
         bw.write(c.getColumnName(i) + ","); 
        } 
        else { 
         bw.write(c.getColumnName(i)); 
        } 

       } 
       bw.write("\r\n"); 
       for (int i = 0; i < rowcount;i++){ 
        c.moveToPosition(i); 
        for (int j = 0;j < colcount;j++){ 
         if (j != colcount-1) 
         { 
          bw.write(c.getString(j)+ ","); 
         }else 
         { 
          bw.write(c.getString(j)); 
         } 

        } 
        bw.write("\r\n"); 
        bw.flush(); 
//      lbl.setText("Exported Successfully."); 

       } 
       File sourceFile = new File(Environment.getExternalStorageDirectory(),"Physical Count.csv"); 
       Intent intent = new Intent(); 
       intent.setAction(Intent.ACTION_SEND); 
       intent.setType("text/plain"); 
       intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(sourceFile)); 
       startActivity(intent); 
      } 
      catch (Exception ex) 
      { 
       if (database.isOpen()){ 
        database.close(); 
       } 
      }