导出文件夹内的数据

问题描述 投票:1回答:1

我正在使用以下代码导出数据。

public void onClick(View v) {
    File sd = Environment.getExternalStorageDirectory();
    String csvFile = "expensesData.xls";
    File directory = new File(sd.getAbsolutePath());
    //create directory if not exist
    if (!directory.isDirectory()) {
        directory.mkdirs();
    }
    try {

        //file path
        File file = new File(directory, csvFile);
        WorkbookSettings wbSettings = new WorkbookSettings();
        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, "Type"));
        sheet.addCell(new Label(1, 0, "Amount"));
        Cursor cursor = db.rawQuery("SELECT expenses_type,amount" +
                "FROM expenses_diary", null);
        if (cursor.moveToFirst()) {
            do {
                String ex_type = cursor.getString(cursor.getColumnIndex("expenses_type"));
                String ex_amount = cursor.getString(cursor.getColumnIndex("amount"));
                int i = cursor.getPosition() + 1;
                sheet.addCell(new Label(0, i, ex_type));
                sheet.addCell(new Label(1, i, ex_amount));
            } while (cursor.moveToNext());
        }
        cursor.close();
        workbook.write();
        workbook.close();
        showToast("Exporting...");
        showToast("Data Exported - expensesData.xls");
    } catch (WriteException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
   }
});

导出的文件存储在Root of Internal Storage中,但我想将该文件存储在文件夹中。(例如,目前在/expensesData.xls中,但我想要ExpensesApp/expensesData.xls

我觉得这很简单,但我是android的新手,所以我不知道。

android export-to-excel
1个回答
3
投票

首先为要创建的目录创建文件类的对象

File folder = new File(Environment.getExternalStorageDirectory() + "/ExpensesApp/");

检查文件夹是否存在,如果该文件夹不存在则创建它

if (!folder.exists())
   folder.mkdir();

然后创建您的xls文件

File file = new File(Environment.getExternalStorageDirectory() + "/ExpensesApp/expensesData.xls");
© www.soinside.com 2019 - 2024. All rights reserved.