• Android修行手册-POI操作Excel文档


    👉关于作者

    专注于Android/Unity和各种游戏开发技巧,以及各种资源分享(网站、工具、素材、源码、游戏等)
    有什么需要欢迎底部卡片私我,交流让学习不再孤单

    在这里插入图片描述

    👉实践过程

    Apache POI 是 Java 领域最完善的 Office 文件读写库

    依赖包前置条件
    poi-scratchpadpoi
    poi-ooxmlpoi, poi-ooxml-schemas
    poi-ooxml-schemasxmlbeans
    poi-examplespoi, poi-scratchpad, poi-ooxml
    ooxml-schemasxmlbeans
    类型文件类型
    POIFSOLE2 Filesystem
    HPSFOLE2 Property Sets
    HSSFExcel XLS
    HSLFPowerPoint PPT
    HWPFWord DOC
    HDGFVisio VSD
    HPBFPublisher PUB
    HSMFOutlook MSG
    OpenXML4JOOXML
    XSSFExcel XLSX
    XSLFPowerPoint PPTX
    XWPFWord DOCX
    Common SSExcel XLS and XLSX

    当只要使用xls格式时、只要导入 POI 即可;
    当还要使用xlsx格式、还要导入 poi-ooxml;
    当需要操作 word、ppt、viso、outlook 等时需要用到 poi-scratchpad。

    同样适用于 Android 领域,但是由于 JDK 和 AndroidSDK 在源码上存在差异,所以原版的 Apache POI 库,并不能直接在安卓上使用

    两个Jar包,poi-android.jar 和 poi-ooxml-schemas.jar
    这里我们用的是修改和精简过后,适合安卓的版本。POI 是3.12版本的,它不是 Apache 官方 POI 包,截止2023年11月我仍然在使用该 Jar 包开发应用,并且没有遇到什么问题。
    需要 Jar 包的欢迎文章最底部卡片 Call 我。
    在这里插入图片描述

    dependencies {
       implementation files('libs\\poi-3.12-android-a.jar')
       implementation files('libs\\poi-ooxml-schemas-3.12-20150511-a.jar')
    }
    
    • 1
    • 2
    • 3
    • 4

    文档 API 可以参考这里,特别注意我们使用的 POI 包不是 Apache 软件基金会的,部分方法及其功能会有所不同!!!

    API:

    • HSSF - 提供读写Microsoft Excel格式档案的功能。
    • XSSF - 提供读写Microsoft Excel OOXML格式档案的功能。
    • HWPF - 提供读写Microsoft Word格式档案的功能。
    • HSLF - 提供读写Microsoft PowerPoint格式档案的功能。
    • HDGF - 提供读写Microsoft Visio格式档案的功能。

    HSSF
    用来操作Office 2007版本前excel.xls文件,XSSF用来操作Office 2007版本后的excel.xlsx文件。HSSF在org.apache.poi.hssf.usermodel包中,实现Workbook 接口,常用组件:
    HSSFWorkbook excel的文档对象
    HSSFSheet excel的表单
    HSSFRow excel的行
    HSSFCell excel的格子单元
    HSSFFont excel字体
    HSSFDataFormat 日期格式
    HSSFHeader sheet头
    HSSFFooter sheet尾(只有打印的时候才能看到效果)
    HSSFCellStyle cell样式
    HSSFDateUtil 日期
    HSSFPrintSetup 打印
    HSSFErrorConstants 错误信息表

    XSSF
    在org.apache.xssf.usemodel包,实现Workbook接口,常用组件:
    XSSFWorkbook excel的文档对象
    XSSFSheet excel的表单
    XSSFRow excel的行
    XSSFCell excel的格子单元
    XSSFFont excel字体
    XSSFDataFormat 日期格式
    和HSSF类似;

    workbook = new XSSFWorkbook(inputStream);   //创建.xlsx格式文件对象
    workbook = new HSSFWorkbook(inputStream);   //创建.xls格式文件对象
    Sheet sheetAt = workbook.getSheetAt(0);   //获取工作表的对象
    Row row = sheetAt.getRow(0);   //获取工作表的行
    int physicalNumberOfCells = row.getPhysicalNumberOfCells();   //获取实际单元格数
    Row.getCell(i)//获取工作表的单元格
    Cell.getCellType()//获得单元格格式
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    Cell.getBooleanCellValue();//获取布尔类型的单元格
    Cell.getNumericCellValue();//获取数字类型的单元格
    Cell.getDateCellValue();//获取日期类型的单元格
    Cell.getNumericCellValue();//获取数值类型的单元格
    Cell.getStringCellValue();//获取字符串类型的单元格
    SheetAt.getPhysicalNumberOfRows(); //获取实际行数
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    //创建工作表的名字
    XSSFSheet sheet = workbook.createSheet(WorkbookUtil.createSafeSheetName("Sheet1"));
    
    • 1
    • 2

    在这里插入图片描述

    Row row = sheet.createRow(int i);  // 创建行
    Cell cell = row.createCell(int i);  // 创建列
    Cell.setCellValue((String) map.get(j));  // 将需要添加到Excel的文本添加到对应的Cell
    //将数据写入文件并保存在指定文件夹
    OutputStream outputStream = context.getContentResolver().openOutputStream(Uri uri);
    XSSFWorkbook.write(outputStream);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    //读取Excel并将其写入数据库
    public List<Map<Integer, Object>> readExcel(Context context, Uri fileUri, String strFileUri) {
            mySQLHelp = new MySQLHelp(context, "mydb.db", null, 1);
            SQLiteDatabase writableDatabase = mySQLHelp.getWritableDatabase();
            excelStr = strFileUri.substring(strFileUri.lastIndexOf("."));
            try {
                inputStream = context.getContentResolver().openInputStream(fileUri);
                if (excelStr.equals(".xlsx")) workbook = new XSSFWorkbook(inputStream);
                else if (excelStr.equals(".xls")) workbook = new HSSFWorkbook(inputStream);
                else workbook = null;
                if (workbook != null) {
                    Sheet sheetAt = workbook.getSheetAt(0);
                    Row row = sheetAt.getRow(0);
                    int physicalNumberOfCells = row.getPhysicalNumberOfCells();//获取实际单元格数
                    Map<Integer, Object> map = new HashMap<>();
                    for (int i = 0; i < physicalNumberOfCells; i++) {//将标题存储到map
                        Object cellFormatValue = getCellFormatValue(row.getCell(i));
                        map.put(i, cellFormatValue);
                    }
                    dataList.add(map);
                    int physicalNumberOfRows = sheetAt.getPhysicalNumberOfRows();//获取最大行数
                    int size = map.size();//获取最大列数
                    contentValues = new ContentValues();
                    for (int i = 1; i < physicalNumberOfRows; i++) {
                        Map<Integer, Object> map1 = new HashMap<>();
                        Row row1 = sheetAt.getRow(i);
                        if (!row1.equals(null)) {
                            for (int j = 0; j < size; j++) {
                                Object cellFormatValue = getCellFormatValue(row1.getCell(j));
                                map1.put(j, cellFormatValue);
                                System.out.println(j);
                            }
                            contentValues.put("materialID", (String) map1.get(0));
                            contentValues.put("materialEncoding", (String) map1.get(1));
                            contentValues.put("materialName", (String) map1.get(2));
                            contentValues.put("materialModel", (String) map1.get(3));
                            contentValues.put("materialSize", (String) map1.get(4));
                            contentValues.put("unit", (String) map1.get(5));
                            contentValues.put("price", (String) map1.get(6));
                            contentValues.put("count", (String) map1.get(7));
                            contentValues.put("manufacturers", (String) map1.get(8));
                            contentValues.put("type", (String) map1.get(9));
                            contentValues.put("receiptor", (String) map1.get(10));
                            contentValues.put("storagelocation", (String) map1.get(11));
                            contentValues.put("materialState", (String) map1.get(12));
                            writableDatabase.insert("module", null, contentValues);
                        } else break;
                        dataList.add(map1);
                    }
                    contentValues.clear();
                    writableDatabase.close();
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return dataList;
        }
        
    private static Object getCellFormatValue(Cell cell) {
            Object cellValue;
            if (cell != null) {
                switch (cell.getCellType()) {
                    case Cell.CELL_TYPE_BOOLEAN:
                        cellValue = cell.getBooleanCellValue();
                        break;
                    case Cell.CELL_TYPE_NUMERIC:
                        cellValue = String.valueOf(cell.getNumericCellValue());
                        break;
                    case Cell.CELL_TYPE_FORMULA:
                        if (DateUtil.isCellDateFormatted(cell)) {
                            cellValue = cell.getDateCellValue();
                        } else {
                            cellValue = cell.getNumericCellValue();
                        }
                        break;
                    case Cell.CELL_TYPE_STRING:
                        cellValue = cell.getStringCellValue();
                        break;
                    default:
                        cellValue = "";
                }
            } else {
                cellValue = "";
            }
            return cellValue;
        }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    //读取数据库数据将其写入Excel并保存到指定路径文件夹
    public void getDataAndSave(Context context,Uri uri) {
            ArrayList<Map<Integer,Object>> arrayList = new ArrayList<>();
            Map<Integer,Object> m = new HashMap<>();
            m.put(0,"物料ID");
            m.put(1,"物料编码");
            m.put(2,"名称");
            m.put(3,"编号");
            m.put(4,"规格");
            m.put(5,"单位");
            m.put(6,"单价");
            m.put(7,"数量");
            m.put(8,"厂家");
            m.put(9,"类别");
            m.put(10,"经手人");
            m.put(11,"存放地点");
            m.put(12,"状态");
            arrayList.add(m);
    
            mySQLHelp = new MySQLHelp(context, "mydb.db", null, 1);
            SQLiteDatabase readableDatabase = mySQLHelp.getReadableDatabase();
            cursor = readableDatabase.rawQuery("select * from module", null);
            while (cursor.moveToNext()) {
                Map<Integer,Object> map = new HashMap<>();
                String materialID = cursor.getString(cursor.getColumnIndex("materialID"));
                String materialEncoding = cursor.getString(cursor.getColumnIndex("materialEncoding"));
                String materialName = cursor.getString(cursor.getColumnIndex("materialName"));
                String materialModel = cursor.getString(cursor.getColumnIndex("materialModel"));
                String materialSize = cursor.getString(cursor.getColumnIndex("materialSize"));
                String unit = cursor.getString(cursor.getColumnIndex("unit"));
                String price = cursor.getString(cursor.getColumnIndex("price"));
                String count = cursor.getString(cursor.getColumnIndex("count"));
                String manufacturers = cursor.getString(cursor.getColumnIndex("manufacturers"));
                String type = cursor.getString(cursor.getColumnIndex("type"));
                String receiptor = cursor.getString(cursor.getColumnIndex("receiptor"));
                String storagelocation = cursor.getString(cursor.getColumnIndex("storagelocation"));
                String materialState = cursor.getString(cursor.getColumnIndex("materialState"));
    
                map.put(0,materialID);
                map.put(1,materialEncoding);
                map.put(2,materialName);
                map.put(3,materialModel);
                map.put(4,materialSize);
                map.put(5,unit);
                map.put(6,price);
                map.put(7,count);
                map.put(8,manufacturers);
                map.put(9,type);
                map.put(10,receiptor);
                map.put(11,storagelocation);
                map.put(12,materialState);
                arrayList.add(map);
            }
            try {
                XSSFWorkbook workbook = new XSSFWorkbook();
                XSSFSheet sheet = workbook.createSheet(WorkbookUtil.createSafeSheetName("Sheet1"));
                Cell cell;
                int size = arrayList.get(0).size();
                for (int i = 0;i < arrayList.size();i++){
                    Row row = sheet.createRow(i);
                    Map<Integer, Object> map = arrayList.get(i);
                    for (int j = 0;j < size;j++){
                        cell = row.createCell(j);
                        cell.setCellValue((String) map.get(j));
                    }
                }
                OutputStream outputStream = context.getContentResolver().openOutputStream(uri);
                workbook.write(outputStream);
                outputStream.flush();
                outputStream.close();
                Toast.makeText(context, "另存成功", Toast.LENGTH_SHORT).show();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
    
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78

    👉其他

    📢作者:小空和小芝中的小空
    📢转载说明-务必注明来源:https://zhima.blog.csdn.net/
    📢这位道友请留步☁️,我观你气度不凡,谈吐间隐隐有王者霸气💚,日后定有一番大作为📝!!!旁边有点赞👍收藏🌟今日传你,点了吧,未来你成功☀️,我分文不取,若不成功⚡️,也好回来找我。

    温馨提示点击下方卡片获取更多意想不到的资源。
    空名先生

  • 相关阅读:
    【JAVA-Day32】精通Java函数:定义、调用和主函数的完整指南
    Docker相关命令
    【C++笔记】C++string类模拟实现
    Java Spring Boot 目录结构介绍
    hashCode
    LeetCode每日一题——324. 摆动排序 II
    Linux自用命令
    批量生产redis测试数据&SQL语句修改varchar类型的字段为json报错
    nginx -s reload, 提示 [emerg] duplicate location “/“
    OpenCV C++案例实战三十三《缺陷检测》
  • 原文地址:https://blog.csdn.net/qq_27489007/article/details/134487891