《Android 开源库》Android OpenCSV

OpenCSV

https://sourceforge.net/projects/opencsv/

使用参考

http://stackoverflow.com/questions/16672074/import-csv-file-to-sqlite-in-android

导出

public class ExportDatabaseToCSV extends AsyncTask<Void, Boolean, Boolean> {

    Context context;
    ProgressDialog dialog;

    public ExportDatabaseToCSV(Context context) {
        this.context = context;
    }

    @Override
    protected void onPreExecute() {
        dialog = new ProgressDialog(context);
        dialog.setTitle("导出CSV文件");
        dialog.setMessage("请稍后...");
        dialog.setCancelable(false);
        dialog.setIcon(android.R.drawable.ic_dialog_info);
        dialog.show();
    }

    @Override
    protected Boolean doInBackground(Void... params) {
        File exportDir = new File(Environment.getExternalStorageDirectory(), "");
        if (!exportDir.exists()) {
            exportDir.mkdirs();
        }

        Date date = new Date(System.currentTimeMillis());
        String filename = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(date);
        File file = new File(exportDir, filename + ".csv");

        try {
            file.createNewFile();
            CSVWriter csvWrite = new CSVWriter(new FileWriter(file));
            StringBuffer check = new StringBuffer();
            check.append("SELECT * FROM NOTE");
            DataBaseHelper db = DataBaseHelper.getInstance(GlobalField.getApplicationContext());
            db.openDataBase();
            Cursor curCSV = db.queryData(check.toString());
			//key -> get the cursor and then using opencsv
            csvWrite.writeNext(curCSV.getColumnNames());
            while (curCSV.moveToNext()) {
                //Which column you want to export you can add over here...
                List<String> list = new ArrayList<>();
                for (int i = 0, length = curCSV.getColumnCount(); i < length; i++) {
                    list.add(curCSV.getString(i));
                }
                String[] arrStr = list.toArray(new String[list.size()]);
                csvWrite.writeNext(arrStr);
            }

            csvWrite.close();
            curCSV.close();
            return true;
        } catch (Exception sqlEx) {
            System.err.println(sqlEx.getMessage());
        }
        return false;
    }

    @Override
    protected void onPostExecute(Boolean result) {
        if (dialog.isShowing()) {
            dialog.dismiss();
        }

        if (result) {
            Toast.makeText(context, "SqLite Data has been Exported!", Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(context, "SqLite Data has not Exported", Toast.LENGTH_LONG).show();
        }
    }
}

导入

public class ImportCVSToSQLiteDataBase extends AsyncTask<String, String, String> {

    Activity activity;
    Context context;
    File file=null;
    private ProgressDialog dialog;

    public ImportCVSToSQLiteDataBase(Context context, Activity activity,File file) {
        this.context=context;
        this.activity=activity;
        this.file=file;
    }

    @Override
    protected void onPreExecute()
    {
        dialog=new ProgressDialog(context);
        dialog.setTitle("Importing Data into SecureIt DataBase");
        dialog.setMessage("Please wait...");
        dialog.setCancelable(false);
        dialog.setIcon(android.R.drawable.ic_dialog_info);
        dialog.show();
    }

@Override
protected String doInBackground(String... params) {

            String data="";
            Log.d(getClass().getName(), file.toString());

           try{
                 CSVReader reader = new CSVReader(new FileReader(file));
                   String [] nextLine;

                  //here I am just displaying the CSV file contents, and you can store your file content into db from while loop...

                    while ((nextLine = reader.readNext()) != null) {

                        // nextLine[] is an array of values from the line

                        String accId=nextLine[0];
                        String acc_name=nextLine[1];

                        data=data+"AccId:"+accId  +"  Account_name:"+acc_name+"\n";//change to save to datebase instead of showing

                      }
                   return data;

            } catch (Exception e) {
                Log.e("Error", "Error for importing file");
            }
        return data="";

  }

protected void onPostExecute(String data)
  {

    if (dialog.isShowing())
    {
        dialog.dismiss();
    }

    if (data.length()!=0)
    {
        Toast.makeText(context, "File is built Successfully!"+"\n"+data, Toast.LENGTH_LONG).show();
    }else{
            Toast.makeText(context, "File fail to build", Toast.LENGTH_SHORT).show();
         }
   }


}

问题

导出的CSV文件如果使用Excel直接打开,可能出现中文乱码

解决办法:
使用记事本打开CSV文件,“文件”->“另存为”,编码方式选择ANSI,保存完毕后,用EXCEL打开这个文件就不会出现乱码的情况。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AndroidKt

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值