4

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

但我无法找到我到底要做什么。谁能以简单的方式详细说明我必须执行什么才能完成此任务。

通过在谷歌上搜索,出现了很多链接,但我无法理解如何一步一步地做到这一点。

我已经关注了这些链接:

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

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

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

4

4 回答 4

9

我的解决方案是在第一步将 sqlite 数据库转换为 csv,然后在第二步将 csv 文件转换为 xls,它对我来说很好,你需要 2 个库(opencsv-1.7.jar; poi-3.8-20120326.罐)

    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();

    }

}


}
于 2013-09-21T22:37:08.927 回答
4

我知道这个问题有点老了,但它为我提供了同一个问题的答案。我已经稍微清理了代码,并通过让我的数据库帮助程序类返回一个 ArrayList 来完全消除编写 csv 文件的需要。不过仍然使用 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();
于 2014-06-14T14:47:20.370 回答
2

将 Android SqliteDb 导出为 CSV 格式

你需要做这些步骤...

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

  2. 然后使用此代码

       
公共类 ExportDatabaseToCSV{
    
    上下文上下文;
    公共 ExportDatabaseToCSV(上下文上下文){
        this.context=上下文;
    }
    
    
    公共无效 exportDataBaseIntoCSV(){
        
      
       CredentialDb db = new CredentialDb(context);//这里 CredentialDb 是我的数据库。你可以创建你的数据库对象。
       文件 exportDir = new File(Environment.getExternalStorageDirectory(), "");        
          
       如果(!exportDir.exists())
          {
              exportDir.mkdirs();
          }

      文件 file = new File(exportDir, "csvfilename.csv");
      
      尝试
      {
          文件.createNewFile();                
          CSVWriter csvWrite = new CSVWriter(new FileWriter(file));
          SQLiteDatabase sql_db = db.getReadableDatabase();//这里创建一个方法,返回SQLiteDatabaseObject.getReadableDatabase();
          光标 curCSV = sql_db.rawQuery("SELECT * FROM "+CredentialDb.TABLE_NAME,null);
          csvWrite.writeNext(curCSV.getColumnNames());
         
          而(curCSV.moveToNext())
              {
                 //你想导出哪一列你可以在这里添加...
                  字符串 arrStr[] ={curCSV.getString(0),curCSV.getString(1), curCSV.getString(2)};
                  csvWrite.writeNext(arrStr);
              }

          csvWrite.close();
          curCSV.close();
      }
      捕获(异常 sqlEx)
      {
          Log.e("错误:", sqlEx.getMessage(), sqlEx);
      }
    }   
}
于 2015-04-25T07:20:57.793 回答
1

除了@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;
    }

希望能帮助到你!

于 2016-08-16T09:19:12.127 回答