Как сумма Veritacal столбцы из базы данных SQLite, а затем экспортировать в лист Excel Андроид


Как я могу суммировать мою колонку с именем Amount через базу данных Sqlite? Я хочу суммировать сумму, которую я ввел, вставляя затем diplay Total of amount в созданный лист Excel.Любезная помощь-это такое приложение.Заранее спасибо.

public void saveExcelFile() {
    try {

        dbHelper = new DBHelper(MainActivity.this);
        final Cursor cursor = dbHelper.getuser(selectedDate);
        //create directory if not exist
        if (!directory.isDirectory()) {
            directory.mkdirs();
        }

        File file = new File(directory, edtDate.getText().toString() + ".xls");
        WorkbookSettings wbSettings = new WorkbookSettings();
        wbSettings.setLocale(new Locale("en", "EN"));
        WritableWorkbook workbook;
        workbook = Workbook.createWorkbook(file, wbSettings);
        //Excel sheet name. 0 represents first sheet
        WritableSheet sheet = workbook.createSheet("userList", 0);
        // column and row
        sheet.addCell(new Label(0, 0, "id"));
        sheet.addCell(new Label(1, 0, "name"));
        sheet.addCell(new Label(2, 0, "email"));
        sheet.addCell(new Label(3, 0, "date"));
        sheet.addCell(new Label(4, 0, "amount"));

        if (cursor.moveToFirst()) {
            do {
                String id = cursor.getString(cursor.getColumnIndex("id"));
                String name = cursor.getString(cursor.getColumnIndex("name"));
                String email = cursor.getString(cursor.getColumnIndex("email"));
                String date = cursor.getString(cursor.getColumnIndex("date"));
                String amount = cursor.getString(cursor.getColumnIndex("amount"));

                int i = cursor.getPosition() + 1;
                sheet.addCell(new Label(0, i, id));
                sheet.addCell(new Label(1, i, name));
                sheet.addCell(new Label(2, i, email));
                sheet.addCell(new Label(3, i, date));
                sheet.addCell(new Label(4, i, amount));
            } while (cursor.moveToNext());
        }

        //closing cursor
        cursor.close();
        workbook.write();
        workbook.close();
        Toast.makeText(getApplication(), "Data Exported in a Excel Sheet", Toast.LENGTH_SHORT).show();
    } catch (WriteException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
1 2

1 ответ:

Делай как..

  1. Добавьте этот файл jar opencsv-1.7.кувшин http://www.java2s.com/Code/Jar/o/Downloadopencsv17jar.htm
  2. а затем используйте этот код

Открытый класс ExportDatabaseToCSV {

Context context;
public ExportDatabaseToCSV(Context context) {
    this.context=context;
}


public void exportDataBaseIntoCSV(){


   CredentialDb db = new CredentialDb(context);//here CredentialDb is my database. you can create your db object.
   File exportDir = new File(Environment.getExternalStorageDirectory(), "");        

   if (!exportDir.exists()) 
      {
          exportDir.mkdirs();
      }

  File file = new File(exportDir, "csvfilename.csv");

  try 
  {
      file.createNewFile();                
      CSVWriter csvWrite = new CSVWriter(new FileWriter(file));
      SQLiteDatabase sql_db = db.getReadableDatabase();//here create a method ,and return SQLiteDatabaseObject.getReadableDatabase();
      Cursor curCSV = sql_db.rawQuery("SELECT * FROM "+CredentialDb.TABLE_NAME,null);
      csvWrite.writeNext(curCSV.getColumnNames());

      while(curCSV.moveToNext())
          {
             //Which column you want to export you can add over here...
              String arrStr[] ={curCSV.getString(0),curCSV.getString(1), curCSV.getString(2)};
              csvWrite.writeNext(arrStr);
          }

      csvWrite.close();
      curCSV.close();
  }
  catch(Exception sqlEx)
  {
      Log.e("Error:", sqlEx.getMessage(), sqlEx);
  }
}   

}

3. Для получения суммы столбца сделайте как показано ниже..

Cursor cursor = db.rawQuery("SELECT SUM(" + DbHelper.CART_TOTAL + ") as Total FROM " + DbHelper.CART_TABLE, null);

 if (cur.moveToFirst()) {

 int total = cursor.getInt(cursor.getColumnIndex("Total"));// get final total