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打开这个文件就不会出现乱码的情况。

Android OpenCSV的更多相关文章

  1. 【英文版本】Android开源项目分类汇总

    Action Bars ActionBarSherlock Extended ActionBar FadingActionBar GlassActionBar v7 appcompat library ...

  2. android github

    Action Bars ActionBarSherlock Extended ActionBar FadingActionBar GlassActionBar v7 appcompat library ...

  3. Android开发免费类库和工具集合

    用于Android开发的免费类库和工具集合,按目录分类. Action Bars ActionBarSherlock Extended ActionBar FadingActionBar GlassA ...

  4. 【原】Android热更新开源项目Tinker源码解析系列之三:so热更新

    本系列将从以下三个方面对Tinker进行源码解析: Android热更新开源项目Tinker源码解析系列之一:Dex热更新 Android热更新开源项目Tinker源码解析系列之二:资源文件热更新 A ...

  5. 配置android sdk 环境

    1:下载adnroid sdk安装包 官方下载地址无法打开,没有vpn,使用下面这个地址下载,地址:http://www.android-studio.org/

  6. Android SwipeRefreshLayout 下拉刷新——Hi_博客 Android App 开发笔记

    以前写下拉刷新 感觉好费劲,要判断ListView是否滚到顶部,还要加载头布局,还要控制 头布局的状态,等等一大堆.感觉麻烦死了.今天学习了SwipeRefreshLayout 的用法,来分享一下,有 ...

  7. Android Studio配置 AndroidAnnotations——Hi_博客 Android App 开发笔记

    以前用Eclicps 用习惯了现在 想学学 用Android Studio 两天的钻研终于 在我电脑上装了一个Android Studio 并完成了AndroidAnnotations 的配置. An ...

  8. Android请求网络共通类——Hi_博客 Android App 开发笔记

    今天 ,来分享一下 ,一个博客App的开发过程,以前也没开发过这种类型App 的经验,求大神们轻点喷. 首先我们要创建一个Andriod 项目 因为要从网络请求数据所以我们先来一个请求网络的共通类. ...

  9. 【原】Android热更新开源项目Tinker源码解析系列之一:Dex热更新

    [原]Android热更新开源项目Tinker源码解析系列之一:Dex热更新 Tinker是微信的第一个开源项目,主要用于安卓应用bug的热修复和功能的迭代. Tinker github地址:http ...

随机推荐

  1. bootstrap基本使用

    bootstrap是封装了css和js代码实现酷炫的效果,所以使用的时候,比如说是列表效果,直接调用它本身定义的函数就ok了 静态文件 把href='..static/..'里面改为url_for静态 ...

  2. Python函数之初体验

    定义函数 在Python中,定义一个函数要使用def语句,依次写出函数名.括号.括号中的参数和冒号:,然后,在缩进块中编写函数体,函数的返回值用return语句返回. 我们先定义一个求字符串长度的函数 ...

  3. 微信小程序学习笔记(4)--------框架之逻辑层

    逻辑层 逻辑层(App Service):小程序框架的逻辑层是由JavaScript编写的,逻辑层将数据进行处理后发送给视图层,同时接受视图层的事件反馈. App进行程序注册,Page进行页面注册 g ...

  4. idea 快键件大全

    最常用快捷键1.Ctrl+E,可以显示最近编辑的文件列表2.Shift+Click可以关闭文件3.Ctrl+[或]可以跳到大括号的开头结尾4.Ctrl+Shift+Backspace可以跳转到上次编辑 ...

  5. angularjs 的controller的三种写法

    AngularJS 的controller其实就是一个方法,它有三种写法: 第一种: <pre name="code" class="javascript" ...

  6. Python面试题之集合推导式、字典推导式

    集合推导式 集合推导式(set comprehensions)跟列表推导式也是类似的, 唯一的区别在于它们使用大括号{}表示. Code: sets = {x for x in range(10)} ...

  7. Oracle 数据库比较日期大小

    在今天或者今天之前作比较:select * from JN_BUS_KJLWSBJBXX where dqsj < to_date('2007-09-07 00:00:00','yyyy-mm- ...

  8. java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[]]

    1.问题描述: 对于创建的springboot项目,通过启动类启动,访问没问题,但打成war部署到tomcat上启动报错,如下: 严重: ContainerBase.addChild: start: ...

  9. application pool can not write to event log

    https://stackoverflow.com/questions/9564420/the-source-was-not-found-but-some-or-all-event-logs-coul ...

  10. NOIP2018没有什么新闻

    noip结束了.站在六中门口,回头望了一眼偌大的校园,萧瑟的秋风卷起残败的落叶,纷纷扬扬地洒落,洒落在OIer的心头. 今年的noip没有什么新闻,有的只是又一次被喷的题,和又一次挂掉的我. Day ...