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. Taking a screen shot of a window using Delphi code is rather easy.

    Taking a screen shot of a window using Delphi code is rather easy. A screen shot (screen capture) is ...

  2. Xamrin开发安卓笔记(二)

    http://www.cnblogs.com/minCS/p/4112617.html Xamrin开发安卓笔记(二)   安装篇 Xamrin开发安卓笔记(一) 昨天调理一天AAPT.EXE 被推出 ...

  3. 有趣的Linux命令,让终端炫起来

    10条真心有趣的Linux命令 动画演示10个有趣但毫无用处的Linux命令 11个无用而有趣的Linux终端彩蛋 lolcat :一个在 Linux 终端中输出彩虹特效的命令行工具

  4. Spring.Net+NHibernate+Castle学习网站

    1.刘冬  http://www.cnblogs.com/GoodHelper/archive/2009/10/16/1584243.html 2.学习资料 http://www.cnblogs.co ...

  5. Kattis - honey【DP】

    Kattis - honey[DP] 题意 有一只蜜蜂,在它的蜂房当中,蜂房是正六边形的,然后它要出去,但是它只能走N步,第N步的时候要回到起点,给出N, 求方案总数 思路 用DP 因为N == 14 ...

  6. cocos2d-x与着色器设计--入门篇(游云凌天原创)

    http://blog.csdn.net/danjinxiangsi/article/details/43949955 着色器(Shader)应用与计算机图形学领域,指一组提供计算机图形资源在渲染时执 ...

  7. VRChat简易教程2-创建一个最基本的世界(world)

    一.准备工作 1 先确保你安装了unity并导入了sdk 教程:https://www.cnblogs.com/cation/p/10311702.html 2 按之前的教程新建一个project并导 ...

  8. NOIP 能量项链

    描述 在Mars星球上,每个Mars人都随身佩带着一串能量项链.在项链上有N颗能量珠.能量珠是一颗有头标记与尾标记的珠子,这些标记对应着某个正整数.并且,对于相邻的两颗珠子,前一颗珠子的尾标记一定等于 ...

  9. [LnOI2019]加特林轮盘赌(DP,概率期望)

    [LnOI2019]加特林轮盘赌(DP,概率期望) 题目链接 题解: 首先特判掉\(p=0/1\)的情况... 先考虑如果\(k=1\)怎么做到\(n^2\)的时间复杂度 设\(f[i]\)表示有\( ...

  10. dedecms 织梦利用arcpagelist标签实现首页arclist分页

    DedeCMS首页arclist分页可以利用arcpagelist标签来实现,这里说一下调用方法:首先必须在首页的<head></head>标签里面引入如下js代码: < ...