简体   繁体   中英

How to generate CSV Files from the content of layout in Android Studio

I'm developing an app where I use TableLayout in Android Studio to display contents inside my app. Now I need to generate CSV file from the contents of the TableLayout in android studio. The contents will be generated from my SQLite database. I tried generating the CSV from my database. But it is not working out. Please tell me how to generate CSV from the Android Studio TableLayout.

This is my DBHelper.Java code

public class DBHelper extends SQLiteOpenHelper {

private static final int VERSION = 2;
public DBHelper(Context context) {
    super(context, DATABASE_NAME, null, VERSION);
}

//class table
public static final String DATABASE_NAME = "attendence.db";
public static final String CLASS_TABLE_NAME = "CLASS_TABLE";
public static final String C_ID = "_CID";
public static final String CLASS_NAME_KEY = "CLASS_NAME";
public static final String SUBJECT_NAME_KEY = "SUBJECT_NAME";

private static final String CREATE_CLASS_TABLE =
        "CREATE TABLE " + CLASS_TABLE_NAME + "( " +
                C_ID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " +
                CLASS_NAME_KEY + " TEXT NOT NULL, " +
                SUBJECT_NAME_KEY + " TEXT NOT NULL, " +
                "UNIQUE (" + CLASS_NAME_KEY + "," + SUBJECT_NAME_KEY + ")" +
                ");";

private static final String DROP_CLASS_TABLE = "DROP TABLE IF EXISTS " + CLASS_TABLE_NAME;
private static final String SELECT_CLASS_TABLE = "SELECT * FROM " + CLASS_TABLE_NAME;

//student table

private static final String STUDENT_TABLE_NAME = "STUDENT_TABLE";
public static final String S_ID = "_SID";
public static final String STUDENT_NAME_KEY = "STUDENT_NAME";
public static final String STUDENT_ROLL_KEY = "ROLL";

private static final String CREATE_STUDENT_TABLE =
        "CREATE TABLE " + STUDENT_TABLE_NAME +
                "( " +
                S_ID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " +
                C_ID + " INTEGER NOT NULL, " +
                STUDENT_NAME_KEY + " TEXT NOT NULL, " +
                STUDENT_ROLL_KEY + " INTEGER, " +
                " FOREIGN KEY ( " + C_ID + ") REFERENCES " + CLASS_TABLE_NAME + "(" + C_ID + ")" +
                ");";

private static final String DROP_STUDENT_TABLE = "DROP TABLE IF EXISTS " + STUDENT_TABLE_NAME;
private static final String SELECT_STUDENT_TABLE = "SELECT * FROM " + STUDENT_TABLE_NAME;


//STATUS TABLE

private static final String STATUS_TABLE_NAME = "STATUS_TABLE";
public static final String STATUS_ID = "_STATUS_ID";
public static final String DATE_KEY = "STATUS_DATE";
public static final String STATUS_KEY = "STATUS";

private static final String CREATE_STATUS_TABLE =
        "CREATE TABLE " + STATUS_TABLE_NAME +
                "(" +
                STATUS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " +
                S_ID + " INTEGER NOT NULL, " +
                C_ID + " INTEGER NOT NULL, " +
                DATE_KEY + " DATE NOT NULL, " +
                STATUS_KEY + " TEXT NOT NULL, " +
                " UNIQUE (" + S_ID + "," + DATE_KEY + ")," +
                " FOREIGN KEY (" + S_ID + ") REFERENCES " + STUDENT_TABLE_NAME + "( " + S_ID + ")," +
                " FOREIGN KEY (" + C_ID + ") REFERENCES " + CLASS_TABLE_NAME + "( " + C_ID + ")" +
                ");";
private static final String DROP_STATUS_TABLE = "DROP TABLE IF EXISTS " + STATUS_TABLE_NAME;
private static final String SELECT_STATUS_TABLE = "SELECT * FROM " + STATUS_TABLE_NAME;

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL(CREATE_CLASS_TABLE);
    db.execSQL(CREATE_STUDENT_TABLE);
    db.execSQL(CREATE_STATUS_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    try {
        db.execSQL(DROP_CLASS_TABLE);
        db.execSQL(DROP_STUDENT_TABLE);
        db.execSQL(DROP_STATUS_TABLE);
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

long addClass(String className,String subjectName){
    SQLiteDatabase database = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(CLASS_NAME_KEY,className);
    values.put(SUBJECT_NAME_KEY,subjectName);

    return database.insert(CLASS_TABLE_NAME,null,values);
}

Cursor getClassTable(){
    SQLiteDatabase database = this.getReadableDatabase();

    return database.rawQuery(SELECT_CLASS_TABLE,null);
}

int deleteClass(long cid){
    SQLiteDatabase database = this.getReadableDatabase();
    return database.delete(CLASS_TABLE_NAME,C_ID+"=?",new String[]{String.valueOf(cid)});
}

long updateClass(long cid,String className,String subjectName){
    SQLiteDatabase database = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(CLASS_NAME_KEY,className);
    values.put(SUBJECT_NAME_KEY,subjectName);

    return database.update(CLASS_TABLE_NAME,values,C_ID+"=?",new String[]{String.valueOf(cid)});
}

long addStudent(long cid,int roll,String name){
    SQLiteDatabase database = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(C_ID,cid);
    values.put(STUDENT_ROLL_KEY,roll);
    values.put(STUDENT_NAME_KEY,name);
    return database.insert(STUDENT_TABLE_NAME,null,values);
}

Cursor getStudentTable(long cid){
    SQLiteDatabase database = this.getReadableDatabase();
    return database.query(STUDENT_TABLE_NAME,null,C_ID+"=?",new String[]{String.valueOf(cid)},null,null,STUDENT_ROLL_KEY);
}

int deleteStudent(long sid){
    SQLiteDatabase database = this.getReadableDatabase();
    return database.delete(STUDENT_TABLE_NAME,S_ID+"=?",new String[]{String.valueOf(sid)});
}

long updateStudent(long sid,String name){
    SQLiteDatabase database = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(STUDENT_NAME_KEY,name);
    return database.update(STUDENT_TABLE_NAME,values,S_ID+"=?",new String[]{String.valueOf(sid)});
}

long addStatus(long sid,long cid, String date, String status){
    SQLiteDatabase database = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(S_ID,sid);
    values.put(C_ID,cid);
    values.put(DATE_KEY,date);
    values.put(STATUS_KEY,status);
    return database.insert(STATUS_TABLE_NAME,null,values);
}

long updateStatus(long sid,String date,String status){
    SQLiteDatabase database = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(STATUS_KEY,status);
    String whereClause = DATE_KEY +"='"+date+"' AND "+S_ID+"="+sid;
    return database.update(STATUS_TABLE_NAME,values,whereClause,null);
}
String getStatus(long sid, String date){
    String status=null;
    SQLiteDatabase database = this.getReadableDatabase();
    String whereClause = DATE_KEY +"='"+date+"' AND "+S_ID+"="+sid;
    Cursor cursor = database.query(STATUS_TABLE_NAME,null,whereClause,null,null,null,null);
    if(cursor.moveToFirst()) {
        status = cursor.getString(cursor.getColumnIndex(STATUS_KEY));
    }
    return status;
}

Cursor getDistinctMonths(long cid){
    SQLiteDatabase database = this.getReadableDatabase();
    return database.query(STATUS_TABLE_NAME,new String[]{DATE_KEY},C_ID+"="+cid,null,"substr("+DATE_KEY+",4,7)",null,null);//23.01.2022
}

}

And This is my btnExport code:-

 btnExport.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(final View view) {
            String directory_path = Environment.getExternalStorageDirectory().getPath() + "/Project Brown/";
            File file = new File(directory_path);
            if (!file.exists()) {
                file.mkdirs();
            }
            // Export SQLite DB as EXCEL FILE
            SQLiteToExcel sqliteToExcel = new SQLiteToExcel(getApplicationContext(), DBHelper.DATABASE_NAME, directory_path);
            sqliteToExcel.exportAllTables("users.xls", new SQLiteToExcel.ExportListener() {
                @Override
                public void onStart() {

                }

                @Override
                public void onCompleted(String filePath) {
                    Toast.makeText(SheetActivity.this, "Excel Exported", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onError(Exception e) {

                }
            });
        }
    });

For a CSV file (not excel file, though excel will read CSV files)

Add to build.gradle file

implementation 'org.apache.commons:commons-csv:1.8'

Then the below should generate a CSV file of any query that returns a Cursor object.

(In the example below this just output full "Class" Table but could be used to output any other Table as well or any other query including joins of Tables)

The example leaves getting a file descriptor up to the user as how to do that varies depending on where the file is to be saved and what Android version used.

try{

    // Getting a file descriptor is up to the user,
    // depend on where and what Android version

    FileWriter fileWriter = new FileWriter(fileDescriptor);

    CSVPrinter printer = new CSVPrinter(fileWriter, CSVFormat.DEFAULT);

    // Get the results of the query from users code
    Cursor cursor = getClassTable();

    // Add column names as first line
    // but as the name might not be proper CSV header names
    // Just output them as plain "data"
    printer.printRecord(cursor.getColumnNames());

    cursor.moveToFirst();
    do {
        // Iterate over columns
        for ( int column = 0; column < cursor.getColumnCount() ; column++) {
           printer.print(cursor.getString(column));
        }
        // Finish line
        printer.println();
    } while(cursor.moveToNext());

    fileWriter.close();

} catch (Exception e) {
   Log.e("bebug", "Exception:" + e.toString());
}

Note this is not tested but is a generic version of using Apache Commons CSV based on what I do in my App to create a csv file of data that is also displayed in a Table layout type format.

Full Docs at https://commons.apache.org/proper/commons-csv/apidocs/org/apache/commons/csv/CSVPrinter.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM