安卓中显示表格并将表格数据以excel格式导出

简介: 安卓中显示表格并将表格数据以excel格式导出

公司项目需要在安卓中显示表格并将表格数据以excel格式导出,表格可以自己定义,最开始想的是使用listView或者recycleView来实现,但是感觉灵活性太差,于是乎就去万能的Github上寻找资源,找了找感觉smartTable写的很好,功能强大且符合需求,好了,开始干活:

显示表格数据

    1、添加 JitPack repository 到你的build文件

allprojects {
  repositories {
    ...
    maven { url 'https://www.jitpack.io' }
  }
  }

     2、添加依赖

dependencies {
         //生成表格显示
    implementation 'com.github.huangyanbin:SmartTable:1.7.1'
  }

    3、在布局文件中使用

<com.bin.david.form.core.SmartTable
        android:id="@+id/materialSmartTable"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center_horizontal"/>

   4、smartTable中向表格中导入数据有多种选择,最简单的即为注解导入:

             a、在实体类的类名上面添加注解,括号中为要显示的表格的名称:

@SmartTable(name="物料清单")
public class BomBean {
}

             b、在需要显示的字段上添加注解:

// id为该字段所在表格排序位置
 @SmartColumn(id =1,name = "列名")
 //如果需要查询到该成员变量里面去,通过设置type实现
 @SmartColumn(type = ColumnType.Child)

             c、设置表格数据:

materialSmartTable = view.findViewById(R.id.materialSmartTable);
materialSmartTable.setData(bomBeanresult);//数据类型为List

导出Excel数据

   1、首先还是需要添加依赖:

//导出excel
    implementation group: 'net.sourceforge.jexcelapi', name: 'jxl', version: '2.6.12'

   2、写一个工具类,用来实现导出Excel文件:

/**
 * @author jiang zhu on 2019/4/14
 */
public class ExcelUtil {
    public static WritableFont arial14font = null;
    public static WritableCellFormat arial14format = null;
    public static WritableFont arial10font = null;
    public static WritableCellFormat arial10format = null;
    public static WritableFont arial12font = null;
    public static WritableCellFormat arial12format = null;
    public final static String UTF8_ENCODING = "UTF-8";
    public final static String GBK_ENCODING = "GBK";
    public static void format() {
        try {
            arial14font = new WritableFont(WritableFont.ARIAL, 14, WritableFont.BOLD);
            arial14font.setColour(jxl.format.Colour.LIGHT_BLUE);
            arial14format = new WritableCellFormat(arial14font);
            arial14format.setAlignment(jxl.format.Alignment.CENTRE);
            arial14format.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);
            arial14format.setBackground(jxl.format.Colour.VERY_LIGHT_YELLOW);
            arial10font = new WritableFont(WritableFont.ARIAL, 10, WritableFont.BOLD);
            arial10format = new WritableCellFormat(arial10font);
            arial10format.setAlignment(jxl.format.Alignment.CENTRE);
            arial10format.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);
            arial10format.setBackground(jxl.format.Colour.LIGHT_BLUE);
            arial12font = new WritableFont(WritableFont.ARIAL, 12);
            arial12format = new WritableCellFormat(arial12font);
            arial12format.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);
        }
        catch (WriteException e) {
            e.printStackTrace();
        }
    }
    /**
     * 初始化
     * @param fileName 文件名称
     * @param colName 需要导出的列名
     */
    public static void initExcel(String fileName, String[] colName) {
        format();
        WritableWorkbook workbook = null;
        try {
            File file = new File(fileName);
            if (!file.exists()) {
                file.delete();
                file.createNewFile();
            }
            workbook = Workbook.createWorkbook(file);
            WritableSheet sheet = workbook.createSheet("物料清单", 0);
            sheet.addCell((WritableCell) new Label(0, 0, fileName, arial14format));
            for (int col = 0; col < colName.length; col++) {
                sheet.addCell(new Label(col, 0, colName[col], arial10format));
            }
            workbook.write();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            if (workbook != null) {
                try {
                    workbook.close();
                }
                catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
    /**
     * 写出excel文件
     * @param objList 数据源
     * @param fileName 文件名称
     * @param c 上下文
     * @param <T> 数据类型
     * @return 写出的Excel文件
     */
    @SuppressWarnings("unchecked")
    public static <T> File writeObjListToExcel(List<T> objList, String fileName, Context c) {
        File file = null;
        if (objList != null && objList.size() > 0) {
            WritableWorkbook writebook = null;
            InputStream in = null;
            file = new File(fileName);
            if (!file.exists()) {
                try {
                    file.delete();
                    file.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                WorkbookSettings setEncode = new WorkbookSettings();
                setEncode.setEncoding(UTF8_ENCODING);
                in = new FileInputStream(file);
                Workbook workbook = Workbook.getWorkbook(in);
                writebook = Workbook.createWorkbook(new File(fileName), workbook);
                WritableSheet sheet = null;
                try {
                    sheet = writebook.getSheet(0);
                } catch (IndexOutOfBoundsException e) {
                    e.printStackTrace();
                }
                for (int j = 0; j < objList.size(); j++) {
                    /*ArrayList<String> list=(ArrayList<String>) objList.get(j);
                    for (int i = 0; i < list.size(); i++) {
                        sheet.addCell(new Label(i, j+1, list.get(i), arial12format));
                    }*/
                    BomBean projectBean = (BomBean) objList.get(j);
                    List<String> list = new ArrayList<>();
                    list.add(projectBean.getMaterialCodeERP());
                    list.add(projectBean.getMaterialName());
                    list.add(projectBean.getSpec());
                    list.add(projectBean.getERPUnit());
                    list.add(projectBean.getNum());
                    list.add(projectBean.getTechnicalProtocol());
                    list.add(projectBean.getBomType());
                    for (int i = 0; i < list.size(); i++) {
                        sheet.addCell(new Label(i, j + 1, list.get(i), arial12format));
                        if (list.get(i).length() <= 4) {
                            //设置列宽
                            sheet.setColumnView(i, list.get(i).length() + 8);
                        } else {
                            //设置列宽
                            sheet.setColumnView(i, list.get(i).length() + 5);
                        }
                    }
                    //设置行高
                    sheet.setRowView(j + 1, 350);
                }
                writebook.write();
                //Toast.makeText(c, "保存成功", Toast.LENGTH_SHORT).show();
            }
            catch (Exception e) {
                e.printStackTrace();
            }
            finally {
                if (writebook != null) {
                    try {
                        writebook.close();
                    }
                    catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                if (in != null) {
                    try {
                        in.close();
                    }
                    catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return file;
    }
    public static Object getValueByRef(Class cls, String fieldName) {
        Object value = null;
        fieldName = fieldName.replaceFirst(fieldName.substring(0, 1), fieldName.substring(0, 1).toUpperCase());
        String getMethodName = "get" + fieldName;
        try {
            Method method = cls.getMethod(getMethodName);
            value = method.invoke(cls);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return value;
    }
}

   3、实现导出Excel:

String filePath = Environment.getExternalStorageDirectory().getAbsolutePath()
                        + "/bhne/";
                File files = new File(filePath);
                if (!files.exists()) {
                    files.mkdirs();
                }
                String[] title = {"物料编码", "物料名称", "物料规格信号", "单位", "物料计算数量", "物料计数协议", "物料类型"};
                String excelFileName = "/" + excelName + ".xls";
                String resultPath = files.getAbsolutePath() + excelFileName;
                Log.e("rultPath", resultPath);
                ExcelUtil.initExcel(resultPath, title);
                File moudleFile = ExcelUtil.writeObjListToExcel(bomBeanresult, resultPath, context);
                if (moudleFile != null) {
                    ToastUtils.showShort("已经保存到本地" + filePath);
                }


基本就这样,剩下的就是逻辑代码了。这是实现demo


目录
相关文章
|
9月前
|
Python
如何根据Excel某列数据为依据分成一个新的工作表
在处理Excel数据时,我们常需要根据列值将数据分到不同的工作表或文件中。本文通过Python和VBA两种方法实现该操作:使用Python的`pandas`库按年级拆分为多个文件,再通过VBA宏按班级生成新的工作表,帮助高效整理复杂数据。
|
9月前
|
数据采集 数据可视化 数据挖掘
用 Excel+Power Query 做电商数据分析:从 “每天加班整理数据” 到 “一键生成报表” 的配置教程
在电商运营中,数据是增长的关键驱动力。然而,传统的手工数据处理方式效率低下,耗费大量时间且易出错。本文介绍如何利用 Excel 中的 Power Query 工具,自动化完成电商数据的采集、清洗与分析,大幅提升数据处理效率。通过某美妆电商的实战案例,详细拆解从多平台数据整合到可视化报表生成的全流程,帮助电商从业者摆脱繁琐操作,聚焦业务增长,实现数据驱动的高效运营。
|
11月前
|
存储 安全 大数据
网安工程师必看!AiPy解决fscan扫描数据整理难题—多种信息快速分拣+Excel结构化存储方案
作为一名安全测试工程师,分析fscan扫描结果曾是繁琐的手动活:从海量日志中提取开放端口、漏洞信息和主机数据,耗时又易错。但现在,借助AiPy开发的GUI解析工具,只需喝杯奶茶的时间,即可将[PORT]、[SERVICE]、[VULN]、[HOST]等关键信息智能分类,并生成三份清晰的Excel报表。告别手动整理,大幅提升效率!在安全行业,工具党正碾压手动党。掌握AiPy,把时间留给真正的攻防实战!官网链接:https://www.aipyaipy.com,解锁更多用法!
|
8月前
|
移动开发 JavaScript
(H5查看CAD)网页CAD提取图纸表格到excel
本文介绍如何通过自定义MxCAD插件,在Web端智能识别CAD图纸中的表格,实现自动合并与高效导出至Excel,提升数据提取效率与准确性。内容涵盖区域选择、图形识别、表格结构重建、单元格合并及内容导出等关键技术,适用于工程图纸数据自动化处理场景。
|
9月前
|
Python
Excel中如何批量重命名工作表与将每个工作表导出到单独Excel文件
本文介绍了如何在Excel中使用VBA批量重命名工作表、根据单元格内容修改颜色,以及将工作表导出为独立文件的方法。同时提供了Python实现导出工作表的代码示例,适用于自动化处理Excel文档。
|
9月前
|
Python
将Excel特定某列数据删除
将Excel特定某列数据删除
|
数据采集 数据可视化 数据挖掘
利用Python自动化处理Excel数据:从基础到进阶####
本文旨在为读者提供一个全面的指南,通过Python编程语言实现Excel数据的自动化处理。无论你是初学者还是有经验的开发者,本文都将帮助你掌握Pandas和openpyxl这两个强大的库,从而提升数据处理的效率和准确性。我们将从环境设置开始,逐步深入到数据读取、清洗、分析和可视化等各个环节,最终实现一个实际的自动化项目案例。 ####
2498 10
|
数据采集 存储 JavaScript
自动化数据处理:使用Selenium与Excel打造的数据爬取管道
本文介绍了一种使用Selenium和Excel结合代理IP技术从WIPO品牌数据库(branddb.wipo.int)自动化爬取专利信息的方法。通过Selenium模拟用户操作,处理JavaScript动态加载页面,利用代理IP避免IP封禁,确保数据爬取稳定性和隐私性。爬取的数据将存储在Excel中,便于后续分析。此外,文章还详细介绍了Selenium的基本设置、代理IP配置及使用技巧,并探讨了未来可能采用的更多防反爬策略,以提升爬虫效率和稳定性。
882 4
|
关系型数据库 MySQL Shell
不通过navicat工具怎么把查询数据导出到excel表中
不通过navicat工具怎么把查询数据导出到excel表中
227 0
|
分布式计算 Hadoop 大数据
从Excel到Hadoop:数据规模的进化之路
从Excel到Hadoop:数据规模的进化之路
336 10