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. java实现简单邮件的发送以及常见问题

    java实现简单邮件的发送以及常见问题 最近遇到个需求需要实现发送邮件的功能,以前做发送邮件功能都是有邮箱用户名密码,通过用户名密码连接对应的SMTP服务器来实现邮件的发送.但是这次用公司内部的邮箱, ...

  2. 8月白盒测试课程 - C C++ 白盒测试实践

    8月白盒测试课程 - C C++ 白盒测试实践http://gdtesting.cn/news.php?id=36

  3. js keyCode(键盘键码)

    摘自:http://blog.csdn.net/dyllove98/article/details/8728657 * 网上收集的KeyCode值方便大家查找: keycode 8 = BackSpa ...

  4. @RequestBody和@ResponseBody的使用情形以及RestTemplate的http报文转换

    @RequestBody和@ResponseBody两个注解,分别完成请求报文到对象和对象到响应报文的转换. @RequestBody 1.@requestBody注解常用来处理content-typ ...

  5. 【HTML5校企公益课】第四天

    1.上午考试没去.. 2.下午跟不上.. 变色.html <!DOCTYPE html> <html> <head> <meta charset=" ...

  6. 【JavaScript】用JS绘制一个球

    参考: 1.http://www.w3school.com.cn/html5/html_5_canvas.asp 2.http://blog.csdn.net/qq_27626333/article/ ...

  7. 运行报警告UserWarning: Unknown extension is not supported and will be removed warn(msg)

    运行python代码,出现如下警告: C:\Users\niko\PycharmProjects\python_new\venv\lib\site-packages\openpyxl\reader\w ...

  8. Runnable、Callable

    Runnable 任务,没有返回值 Callable 任务,又返回值 Runnable与Callable 相同点: 1. 都是接口: 2. 用来编写多线程程序: 3. 都需要调用Thread.star ...

  9. toLatin1 toLocal8Bit

    toLatin1.toLocal8Bit都是QString转QByteArray的方法,Latin1代表ASCII,Local8Bit代表unicode

  10. 源码编译配置lnmp部署zabbix

    环境说明: [root@wcy ~]# cat /etc/redhat-release CentOS release 6.9 (Final) [root@wcy ~]# uname -a Linux ...