android - 导出文件夹内的数据

标签 android export-to-excel

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

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

导出的文件存储在内部存储的根目录中,但我想将该文件存储在文件夹中。(例如,当前在 /expensesData.xls 中,但我想要 ExpensesApp/expensesData.xls.

我认为这很简单,但在 android 中是新的,所以我不知道。

最佳答案

首先为你想创建的目录创建一个文件类的对象

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

判断文件夹是否存在,不存在则创建

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

然后创建你的xls文件

File file = new File(Environment.getExternalStorageDirectory() + "/ExpensesApp/expensesData.xls");

关于android - 导出文件夹内的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49108716/

相关文章:

android - 如何使用 Intent 服务通过服务更新 UI 上传多个图像

db2 - 使用列名从 db2 导出数据

html - 空白 : pre; ignored/inconsistent inside <td> in export to (save as) . xls

php - 从企业应用程序中使用 PHP 从 MySQL 数据生成大型 Excel 文件

android - 布局验证不同于加载程序 android Studio

android - Oreo (8.0) - 以编程方式删除短信

java - Android - 从 ListViewAdapter 中删除项目然后刷新

jquery - Android 2.2.2 上的浏览​​器未使用 jQuery 获取 JSONP

java - jasperreports 大型 Excel 文件

c# - 使用 c# 将 SQL Server 2008 数据库中的表导出到 excel