【问题标题】:Exporting SQLite Data to CSV outputs only last entry of the database in the CSV File将 SQLite 数据导出到 CSV 仅输出 CSV 文件中数据库的最后一个条目
【发布时间】:2019-09-07 12:15:24
【问题描述】:

我正在尝试为我的大学制作一个考勤应用程序。我使用 SQLite 进行数据存储(学生名单、考勤数据等) 我希望将考勤数据导出为 CSV 文件。问题是,当我导出文件时,只有 SQLite Db 的最后一个条目被写入 CSV。我附上了下面的代码以便更好地理解。

public void exportExcelSheet() {

        DatabaseHandler mDbHandler = new DatabaseHandler(mActivity);
        File exportDir = new File(Environment.getExternalStorageDirectory(), "");
        if (!exportDir.exists())
        {
            exportDir.mkdirs();
        }

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

        String[] ColumnNames = {"Roll No.","Name","LA","LT","% age"};

        String studentInfoQuery = "SELECT * FROM StudentList";
        Cursor studentsListCursor = mDbHandler.execQuery(studentInfoQuery);

        studentsListCursor.moveToFirst();

        while(!studentsListCursor.isAfterLast()) {


            String AttendanceListQuery = "SELECT * FROM AttendanceSheet WHERE StudRoll = '" + studentsListCursor.getPosition() + "';";
            String AttendanceQuery = "SELECT * FROM AttendanceSheet WHERE StudRoll = '" + studentsListCursor.getPosition() + "' AND isPresent = 1";


            int attendancePercent = 0;
            Cursor totalClasses = mDbHandler.execQuery(AttendanceListQuery);
            Cursor attendedClasses = mDbHandler.execQuery(AttendanceQuery);

            if (totalClasses == null) {
                Log.d("profile", "totalClasses null");
            }

            if (attendedClasses == null) {
                Log.d("profile", "attendedClasses null");
            }

            if (totalClasses != null && attendedClasses != null) {
                totalClasses.moveToFirst();
                attendedClasses.moveToFirst();

                try {
                    attendancePercent = (int) (((float) attendedClasses.getCount() / totalClasses.getCount()) * 100);
                } catch (Exception e) {
                    attendancePercent = -1;
                }
            }

            assert attendedClasses != null;
            assert totalClasses != null;
            String showAttendedLectures = String.valueOf(attendedClasses.getCount());
            String showTotalLectures = String.valueOf(totalClasses.getCount());
            //String showMissedLectures = String.valueOf(totalClasses.getCount() - attendedClasses.getCount());
            String AttendancePercentage = String.valueOf(attendancePercent);

            try
            {
                if(!file.exists()){
                    file.createNewFile();

                }

                CSVWriter csvWrite = new CSVWriter(new FileWriter(file));

                csvWrite.writeNext(ColumnNames);
                    String[] arrStr ={studentsListCursor.getString(1),studentsListCursor.getString(0), showAttendedLectures, showTotalLectures, AttendancePercentage + " %"};
                    csvWrite.writeNext(arrStr);
                studentsListCursor.moveToNext();
                csvWrite.close();
            }
            catch(Exception sqlException)
            {
                Toast.makeText(mActivity, "FAILED", Toast.LENGTH_SHORT).show();
                Log.e("MainActivity", sqlException.getMessage(), sqlException);
            }

            Toast.makeText(mActivity, "Saved", Toast.LENGTH_SHORT).show();
        }
    }
}

Here's What the CSV File looks like.

【问题讨论】:

    标签: java android android-sqlite export-to-csv


    【解决方案1】:

    这段代码中只有一个小错误,即 csvWriter 对象在执行 do-while 循环时创建,因此最后一个输出 CSV 文件仅从光标中提取了单行和最后一行。 这应该可以解决问题:

    public void exportExcelSheet() {
        DatabaseHandler mDbHandler = new DatabaseHandler(mActivity);
        File exportDir = new File(Environment.getExternalStorageDirectory(), "");
        if (!exportDir.exists()) {
            exportDir.mkdirs();
        }
    
        File file = new File(exportDir, "Report.csv");
    
        // ============== CHANGE ==============
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
    
        }
    
        String[] ColumnNames = {"Roll No.", "Name", "LA", "LT", "% age"};
    
        // ============== CHANGE ==============
        CSVWriter csvWrite = new CSVWriter(new FileWriter(file));
        csvWrite.writeNext(ColumnNames);
    
        String studentInfoQuery = "SELECT * FROM StudentList";
        Cursor studentsListCursor = mDbHandler.execQuery(studentInfoQuery);
    
        studentsListCursor.moveToFirst();
    
        // ============== CHANGE ==============
        do {
            String AttendanceListQuery = "SELECT * FROM AttendanceSheet WHERE StudRoll = '" + studentsListCursor.getPosition() + "';";
            String AttendanceQuery = "SELECT * FROM AttendanceSheet WHERE StudRoll = '" + studentsListCursor.getPosition() + "' AND isPresent = 1";
    
    
            int attendancePercent = 0;
            Cursor totalClasses = mDbHandler.execQuery(AttendanceListQuery);
            Cursor attendedClasses = mDbHandler.execQuery(AttendanceQuery);
    
            if (totalClasses == null) {
                Log.d("profile", "totalClasses null");
            }
    
            if (attendedClasses == null) {
                Log.d("profile", "attendedClasses null");
            }
    
            if (totalClasses != null && attendedClasses != null) {
                totalClasses.moveToFirst();
                attendedClasses.moveToFirst();
    
                try {
                    attendancePercent = (int) (((float) attendedClasses.getCount() / totalClasses.getCount()) * 100);
                } catch (Exception e) {
                    attendancePercent = -1;
                }
            }
    
            assert attendedClasses != null;
            assert totalClasses != null;
            String showAttendedLectures = String.valueOf(attendedClasses.getCount());
            String showTotalLectures = String.valueOf(totalClasses.getCount());
            //String showMissedLectures = String.valueOf(totalClasses.getCount() - attendedClasses.getCount());
            String AttendancePercentage = String.valueOf(attendancePercent);
    
            try {
                String[] arrStr = {studentsListCursor.getString(1), studentsListCursor.getString(0), showAttendedLectures, showTotalLectures, AttendancePercentage + " %"};
                csvWrite.writeNext(arrStr);
                // ============== CHANGE ==============
                // studentsListCursor.moveToNext();
            } catch (Exception sqlException) {
                Toast.makeText(mActivity, "FAILED", Toast.LENGTH_SHORT).show();
                Log.e("MainActivity", sqlException.getMessage(), sqlException);
            }
    
            Toast.makeText(mActivity, "Saved", Toast.LENGTH_SHORT).show();
        }
        // ============== CHANGE ==============
        while (studentsListCursor.moveToNext());
    
        csvWrite.close();
    }
    

    【讨论】:

    • 试过了,还是一样的问题。 :(
    • 非常感谢兄弟,这是一个愚蠢的错误,非常感谢您对更改的评论,它让我意识到自己的错误并帮助我纠正错误,而不仅仅是复制粘贴。
    • 解释如何解决问题将改善您的答案
    • @Marged 感谢您的建议,他的代码中有一个小错误,即 csvWriter 对象在执行 do-while 循环时创建,因此最后一个输出 CSV 文件只有单行和最后一行从游标中获取。
    • 我知道 ;-) 但是现在你改进了 cmets,而不是答案
    【解决方案2】:

    对于其他寻找类似问题答案的人,根据 Dheeraj 的代码和另一个小改动,最终的 WORKING Code 将是 -

     public void exportExcelSheet() throws IOException {
        DatabaseHandler mDbHandler = new DatabaseHandler(mActivity);
        File exportDir = new File(Environment.getExternalStorageDirectory(), "");
        if (!exportDir.exists()) {
            exportDir.mkdirs();
        }
    
        File file = new File(exportDir, "Report.csv");
    
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
    
        }
    
        String[] ColumnNames = {"Roll No.", "Name", "LA", "LT", "% age"};
    
        CSVWriter csvWrite = new CSVWriter(new FileWriter(file));
        csvWrite.writeNext(ColumnNames);
    
        String studentInfoQuery = "SELECT * FROM StudentList";
        Cursor studentsListCursor = mDbHandler.execQuery(studentInfoQuery);
    
        studentsListCursor.moveToFirst();
    
        do {
            int studentRoll = studentsListCursor.getPosition() + 1;
            String AttendanceListQuery = "SELECT * FROM AttendanceSheet WHERE StudRoll = '" + studentRoll + "';";
            String AttendanceQuery = "SELECT * FROM AttendanceSheet WHERE StudRoll = '" + studentRoll + "' AND isPresent = 1";
    
            int attendancePercent = 0;
            Cursor totalClasses = mDbHandler.execQuery(AttendanceListQuery);
            Cursor attendedClasses = mDbHandler.execQuery(AttendanceQuery);
    
            if (totalClasses == null) {
                Log.d("profile", "totalClasses null");
            }
    
            if (attendedClasses == null) {
                Log.d("profile", "attendedClasses null");
            }
    
            if (totalClasses != null && attendedClasses != null) {
                totalClasses.moveToFirst();
                attendedClasses.moveToFirst();
    
                try {
                    attendancePercent = (int) (((float) attendedClasses.getCount() / totalClasses.getCount()) * 100);
                } catch (Exception e) {
                    attendancePercent = -1;
                }
            }
    
            assert attendedClasses != null;
            assert totalClasses != null;
            String showAttendedLectures = String.valueOf(attendedClasses.getCount());
            String showTotalLectures = String.valueOf(totalClasses.getCount());
            //String showMissedLectures = String.valueOf(totalClasses.getCount() - attendedClasses.getCount());
            String AttendancePercentage = String.valueOf(attendancePercent);
    
            try {
                String[] arrStr = {studentsListCursor.getString(1), studentsListCursor.getString(0), showAttendedLectures, showTotalLectures, AttendancePercentage + " %"};
                csvWrite.writeNext(arrStr);
    
            } catch (Exception sqlException) {
                Toast.makeText(mActivity, "FAILED", Toast.LENGTH_SHORT).show();
                Log.e("MainActivity", sqlException.getMessage(), sqlException);
            }
    
            Toast.makeText(mActivity, "Saved", Toast.LENGTH_SHORT).show();
        }
    
        while (studentsListCursor.moveToNext());
    
        csvWrite.close();
    }
    

    【讨论】:

      猜你喜欢
      • 2015-09-30
      • 2016-01-18
      • 2013-09-10
      • 1970-01-01
      • 1970-01-01
      • 2013-03-19
      • 2021-01-09
      • 2011-05-04
      • 1970-01-01
      相关资源
      最近更新 更多