Android程序将SQLite数据库转换为Excel

I want to change the sqlite database .db file to excel.

但是无法find我所要做的。 任何人都可以用简单的方式来说明我要完成这个任务。

通过在Google上search,出现了很多链接,但是我无法一步步了解这一点。

我跟着这个链接:

1. 如何将excel表单转换为android中的sqlite数据库

2. SQlite数据库以编程方式转换为Android中的Excel文件格式

3. http://opencsv.sourceforge.net/

我的解决scheme是在第一步将sqlite数据库转换为csv,然后在第二步中将csv文件转换为xls,对我来说工作正常,您将需要2个库(opencsv-1.7.jar; poi-3.8-20120326)。jar)

  public class ExportDatabaseCSVTask extends AsyncTask<String, Void, Boolean> { private final ProgressDialog dialog = new ProgressDialog(DatabaseExampleActivity.this); @Override protected void onPreExecute() { this.dialog.setMessage("Exporting database..."); this.dialog.show(); } protected Boolean doInBackground(final String... args) { File dbFile=getDatabasePath("database_name"); //AABDatabaseManager dbhelper = new AABDatabaseManager(getApplicationContext()); AABDatabaseManager dbhelper = new AABDatabaseManager(DatabaseExampleActivity.this) ; System.out.println(dbFile); // displays the data base path in your logcat File exportDir = new File(Environment.getExternalStorageDirectory(), ""); if (!exportDir.exists()) { exportDir.mkdirs(); } File file = new File(exportDir, "excerDB.csv"); try { if (file.createNewFile()){ System.out.println("File is created!"); System.out.println("myfile.csv "+file.getAbsolutePath()); }else{ System.out.println("File already exists."); } CSVWriter csvWrite = new CSVWriter(new FileWriter(file)); //SQLiteDatabase db = dbhelper.getWritableDatabase(); Cursor curCSV=db.getdb().rawQuery("select * from " + db.TABLE_NAME,null); csvWrite.writeNext(curCSV.getColumnNames()); while(curCSV.moveToNext()) { String arrStr[] ={curCSV.getString(0),curCSV.getString(1),curCSV.getString(2)}; /*curCSV.getString(3),curCSV.getString(4)};*/ csvWrite.writeNext(arrStr); } csvWrite.close(); curCSV.close(); /*String data=""; data=readSavedData(); data= data.replace(",", ";"); writeData(data);*/ return true; } catch(SQLException sqlEx) { Log.e("MainActivity", sqlEx.getMessage(), sqlEx); return false; } catch (IOException e) { Log.e("MainActivity", e.getMessage(), e); return false; } } protected void onPostExecute(final Boolean success) { if (this.dialog.isShowing()) { this.dialog.dismiss(); } if (success) { Toast.makeText(DatabaseExampleActivity.this, "Export succeed", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(DatabaseExampleActivity.this, "Export failed", Toast.LENGTH_SHORT).show(); } }} 

将CSV导出到XLS部分

  public class CSVToExcelConverter extends AsyncTask<String, Void, Boolean> { private final ProgressDialog dialog = new ProgressDialog(DatabaseExampleActivity.this); @Override protected void onPreExecute() {this.dialog.setMessage("Exporting to excel..."); this.dialog.show();} @Override protected Boolean doInBackground(String... params) { ArrayList arList=null; ArrayList al=null; //File dbFile= new File(getDatabasePath("database_name").toString()); File dbFile=getDatabasePath("database_name"); String yes= dbFile.getAbsolutePath(); String inFilePath = Environment.getExternalStorageDirectory().toString()+"/excerDB.csv"; outFilePath = Environment.getExternalStorageDirectory().toString()+"/test.xls"; String thisLine; int count=0; try { FileInputStream fis = new FileInputStream(inFilePath); DataInputStream myInput = new DataInputStream(fis); int i=0; arList = new ArrayList(); while ((thisLine = myInput.readLine()) != null) { al = new ArrayList(); String strar[] = thisLine.split(","); for(int j=0;j<strar.length;j++) { al.add(strar[j]); } arList.add(al); System.out.println(); i++; }} catch (Exception e) { System.out.println("shit"); } try { HSSFWorkbook hwb = new HSSFWorkbook(); HSSFSheet sheet = hwb.createSheet("new sheet"); for(int k=0;k<arList.size();k++) { ArrayList ardata = (ArrayList)arList.get(k); HSSFRow row = sheet.createRow((short) 0+k); for(int p=0;p<ardata.size();p++) { HSSFCell cell = row.createCell((short) p); String data = ardata.get(p).toString(); if(data.startsWith("=")){ cell.setCellType(Cell.CELL_TYPE_STRING); data=data.replaceAll("\"", ""); data=data.replaceAll("=", ""); cell.setCellValue(data); }else if(data.startsWith("\"")){ data=data.replaceAll("\"", ""); cell.setCellType(Cell.CELL_TYPE_STRING); cell.setCellValue(data); }else{ data=data.replaceAll("\"", ""); cell.setCellType(Cell.CELL_TYPE_NUMERIC); cell.setCellValue(data); } //*/ // cell.setCellValue(ardata.get(p).toString()); } System.out.println(); } FileOutputStream fileOut = new FileOutputStream(outFilePath); hwb.write(fileOut); fileOut.close(); System.out.println("Your excel file has been generated"); } catch ( Exception ex ) { ex.printStackTrace(); } //main method ends return true; } protected void onPostExecute(final Boolean success) { if (this.dialog.isShowing()) { this.dialog.dismiss(); } if (success) { Toast.makeText(DatabaseExampleActivity.this, "file is built!", Toast.LENGTH_LONG).show(); } else { Toast.makeText(DatabaseExampleActivity.this, "file fail to build", Toast.LENGTH_SHORT).show(); } } } 

我知道这个问题有点老,但它给了我同样问题的答案。 我已经清理了一些代码,并完成了编写一个csv文件的需要,通过让我的数据库辅助类返回一个ArrayList。 尽pipe如此,仍然使用Apache POI。

 File folder =new File(Environment.getExternalStorageDirectory()+APP_FILES_PATH); if(!folder.exists()) { folder.mkdir(); } DatabaseHelper dbHelper = DatabaseHelper.getInstance(context); ArrayList<String[]> exts = dbHelper.getExtinguisherArray(1); HSSFWorkbook hwb = new HSSFWorkbook(); HSSFSheet sheet = hwb.createSheet("extinguishers"); for(int x = 0; x < exts.size(); x++) { String[] arr = exts.get(x); HSSFRow row = sheet.createRow(x); for(int i = 0; i< arr.length; i++) { HSSFCell cell = row.createCell(i); String data = arr[i]; cell.setCellValue(data); } } FileOutputStream fileOut = new FileOutputStream(Environment.getExternalStorageDirectory()+APP_FILES_PATH+"file.xls"); hwb.write(fileOut); fileOut.close(); 

将Android SqliteDb导出为CSV格式

你需要做这些步骤…

  1. 添加这个jar文件opencsv-1.7.jar http://www.java2s.com/Code/Jar/o/Downloadopencsv17jar.htm

  2. 然后使用这个代码

       
公共类ExportDatabaseToCSV {

    上下文环境;
     public ExportDatabaseToCSV(Context context){
         this.context =上下文;
     }


     public void exportDataBaseIntoCSV(){


        CredentialDb db = new CredentialDb(context); //这里CredentialDb是我的数据库。 你可以创build你的数据库对象。
        File exportDir = new File(Environment.getExternalStorageDirectory(),“”);        

       如果(!exportDir.exists()) 
           {
               exportDir.mkdirs();
           }

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

      尝试 
       {
           file.createNewFile();                
           CSVWriter csvWrite = new CSVWriter(new FileWriter(file));
           SQLiteDatabase sql_db = db.getReadableDatabase(); //这里创build一个方法,并返回SQLiteDatabaseObject.getReadableDatabase();
          游标curCSV = sql_db.rawQuery(“SELECT * FROM”+ CredentialDb.TABLE_NAME,null);
           csvWrite.writeNext(curCSV.getColumnNames());

          而(curCSV.moveToNext())
               {
                  //你想要导出哪一列你可以在这里添加...
                   String arrStr [] = {curCSV.getString(0),curCSV.getString(1),curCSV.getString(2)};
                   csvWrite.writeNext(arrStr);
               }

           csvWrite.close();
           curCSV.close();
       }
       catch(exceptionsqlEx)
       {
           Log.e(“Error:”,sqlEx.getMessage(),sqlEx);
       }
     }   
 }

除了@ user2324120的回答,以及我们在Android中,您可以直接将库添加到gradle(因此您不需要下载jar):

 compile 'com.opencsv:opencsv:3.7' compile 'org.apache.poi:poi:3.14' 

我也做了一个不同的方式,一种更可定制的方式(没有无用的CSV转换)。 这里有几点意见:

  public static Pair<Boolean, String> exportToXLS(Context context, boolean byAuthor) { try { HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet sheet = workbook.createSheet(context.getString(R.string.sheet_name)); // Good for localization initSheetColumns(context, workbook, sheet, byAuthor); addBooksToSheet(sheet, byAuthor); setColumsWidth(sheet); OutputStream outputStream = new FileOutputStream(new File(Methods.getDownloadsDirectory(), byAuthor ? context.getString(R.string.mylibrary_by_author_xls) : context.getString(R.string.mylibrary_xls)).getAbsolutePath()); workbook.write(outputStream); outputStream.flush(); outputStream.close(); return new Pair<>(true, context.getString(R.string.database_saved)); } catch (Exception e) { e.printStackTrace(); return new Pair<>(false, context.getString(R.string.an_error_has_occured_during_xls_file_creation)); } } private static void initSheetColumns(Context context, HSSFWorkbook workbook, HSSFSheet sheet, boolean byAuthor) { HSSFRow row = sheet.createRow(0); HSSFCell cell = row.createCell(0); cell.setCellValue(byAuthor ? context.getString(R.string.db_author) : context.getString(R.string.db_title)); cell = row.createCell(1); cell.setCellValue(byAuthor ? context.getString(R.string.db_title) : context.getString(R.string.db_author)); cell = row.createCell(2); cell.setCellValue(context.getString(R.string.db_publisheddate)); /* etc. */ boldHeaders(workbook, row); } private static void boldHeaders(HSSFWorkbook workbook, HSSFRow row) { HSSFCellStyle style = workbook.createCellStyle(); /* Do your own style ... */ for (int i = 0; i < 8; i++) { row.getCell(i).setCellStyle(style); } } // Allow data personalisation and localisation if needed private static void addBooksToSheet(HSSFSheet sheet, boolean byAuthor) { int i = 1; List<Book> books = Book.listAll(Book.class); // I use Sugar library here, if you're not just make a simple db query to get your objects Collections.sort(books, byAuthor ? Book.bookAuthorComparator : Book.bookNameComparator); for (Book book : books) { HSSFRow row = sheet.createRow(i); HSSFCell cell = row.createCell(0); cell.setCellValue(byAuthor ? getBookValue(book, true) : book.getTitle()); cell = row.createCell(1); cell.setCellValue(byAuthor ? book.getTitle() : getBookValue(book, false)); cell = row.createCell(2); cell.setCellValue(book.getPublishedDate()); /* etc. */ i++; } } private static void setColumsWidth(HSSFSheet sheet) { for (int i = 0; i < 8; i++) { sheet.setColumnWidth(i, 255 * getMaxNumCharacters(sheet, i)); // Autosize not working on Android } } // My method to get the max num char, if it can hekp public static int getMaxNumCharacters(Sheet sheet, int column) { int max = 0; for (int rowIndex = 0; rowIndex <= sheet.getLastRowNum(); rowIndex++) { Row row = sheet.getRow(rowIndex); if (row == null) { continue; } Cell cell = row.getCell(column); if (cell != null) { int nb = cell.getStringCellValue().length(); if (nb > max) { max = nb; } } } max = (int) (max * 1.1); if (max > 255) { return 255; // max 255 char for width } return max; } 

希望能帮助到你!