• <noscript id="e0iig"><kbd id="e0iig"></kbd></noscript>
  • <td id="e0iig"></td>
  • <option id="e0iig"></option>
  • <noscript id="e0iig"><source id="e0iig"></source></noscript>
  • android讀寫excel文件

    標簽: android  excel

    android操作excel文件需要用到第三方jar文件,共有兩種jar文件可以供android來操作excel文件:poi.jar和jxl.jar.兩者這要的區別在于poi.jar可以操作excel2007之前的,而jxl.jar只能操作excel2003以前的。接下來分別實現這兩種方式的excel文件讀寫。

    ·poi.jar

    下載poi.jar包

    http://poi.apache.org/download.html

    下載的zip壓縮包中有很多jar包,因為我這里沒有用到excel2007,所以我就添加poi-xxxx.jar到工程中。如果需要使用excel2007,則添加poi-ooxml的jar包。注:這兩個jar包不能同時添加,否則會提示duplicate錯誤。

    新建一個excel文件

    private static void initWorkbook(String path) {
            Workbook mExcelWorkbook = new HSSFWorkbook();
            //標題欄單元格特征
    //        CellStyle titleStyle = createTitleCellStyle();
    
            //創建execl中的一個表
            Sheet sheet = mExcelWorkbook.createSheet();
            mExcelWorkbook.setSheetName(0, "mi-cms-test");
            //創建標題欄1
            Row titleRow1 = sheet.createRow(0);
            // 設置標題欄高度
            titleRow1.setHeightInPoints(60);
    //        titleRow1.setRowStyle(titleStyle);
    
            //創建標題欄第1個標題
            Cell cell0 = titleRow1.createCell(0);
            cell0.setCellValue("");
    
            //創建標題欄第2個標題
            Cell cell1 = titleRow1.createCell(1);
            cell1.setCellValue("信號強度");
            sheet.addMergedRegion(CellRangeAddress.valueOf("$B$1:$D$1"));
    
            //創建標題欄第3個標題
            Cell cell2 = titleRow1.createCell(4);
            cell2.setCellValue("數據包");
            sheet.addMergedRegion(CellRangeAddress.valueOf("$E$1:$G$1"));
    
            //創建標題欄第4個標題
            Cell cell3 = titleRow1.createCell(7);
            cell3.setCellValue("");
    
            //創建標題欄第5個標題
            Cell cell4 = titleRow1.createCell(8);
            cell4.setCellValue("心率");
            sheet.addMergedRegion(CellRangeAddress.valueOf("$I$1:$J$1"));
    
            //創建標題欄2
            Row titleRow2 = sheet.createRow(1);
            // 藍牙地址/***
            Cell cell10 = titleRow2.createCell(0);
            cell10.setCellValue("藍牙地址,***");
    
            // 信號強度
            Cell cell11 = titleRow2.createCell(1);
            cell11.setCellValue("最小");
            Cell cell12 = titleRow2.createCell(2);
            cell12.setCellValue("最大");
            Cell cell13 = titleRow2.createCell(3);
            cell13.setCellValue("平均");
    
            // 數據包
            Cell cell14 = titleRow2.createCell(4);
            cell14.setCellValue("總計");
            Cell cell15 = titleRow2.createCell(5);
            cell15.setCellValue("丟失數");
            Cell cell16 = titleRow2.createCell(6);
            cell16.setCellValue("丟失率");
    
            // 電量
            Cell cell17 = titleRow2.createCell(7);
            cell17.setCellValue("電量");
    
            // 心率
            Cell cell18 = titleRow2.createCell(8);
            cell18.setCellValue("最大");
            Cell cell19 = titleRow2.createCell(9);
            cell19.setCellValue("最小");
    
            writeFile(mExcelWorkbook, path);
        }
    
        /**
         * 將Excle表格寫入文件中
         *
         * @param workbook
         * @param fileName
         */
        private static void writeFile(Workbook workbook, String fileName) {
            FileOutputStream outputStream = null;
            try {
                outputStream = new FileOutputStream(fileName);
                workbook.write(outputStream);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (outputStream != null) {
                        outputStream.close();
                    }
                    if (workbook != null) {
                        workbook.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

    上面的代碼創建了一個excel文件,添加了一個名為”mi-cms-test“的Sheet頁,增加一些標題,并對一些標題的單元格進行合并,生成的excel文件內容格式如下:
    這里寫圖片描述

    獲取指定的excel文件

     public static void getWorkbook(String filename) throws IOException {
            if (null != filename) {
                String fileType = filename.substring(filename.lastIndexOf("."),
                        filename.length());
                FileInputStream fileStream = new FileInputStream(new File(filename));
                if (".xls".equals(fileType.trim().toLowerCase())) {
                   Workbook mExcelWorkbook = new HSSFWorkbook(fileStream);// 創建 Excel 2003 工作簿對象
                }
            }
        }

    操作excel文件,追加數據到excel文件

    public static boolean writeExcel(String dir, String fileName, TestInfo testInfo) {
            String path = null;
            try {
                path = initExcelWorkbook(dir, fileName);
            } catch (IOException e) {
                e.printStackTrace();
            }
            Sheet sheet = mExcelWorkbook.getSheetAt(0);
            // 獲取當前行數的下一行
            Row row = sheet.createRow(sheet.getLastRowNum() + 1);
    //        CellStyle rowCellStyle = createRowCellStyle();
    //        row.setRowStyle(rowCellStyle);
    
            // 藍牙地址/***
            Cell cell0 = row.createCell(0);
            cell0.setCellValue(testInfo.getDeviceAddress() + ", " + testInfo.getDeviceSerialNum());
    
            // 信號強度
            Cell cell1 = row.createCell(1);
            cell1.setCellValue(testInfo.getRssiMin());
            Cell cell2 = row.createCell(2);
            cell2.setCellValue(testInfo.getRssiMax());
            Cell cell3 = row.createCell(3);
            cell3.setCellValue(testInfo.getRssiAvg());
    
            // 數據包
            Cell cell4 = row.createCell(4);
            cell4.setCellValue(testInfo.getDataTotal());
            Cell cell5 = row.createCell(5);
            cell5.setCellValue(testInfo.getDataMissed());
            Cell cell6 = row.createCell(6);
            cell6.setCellValue(testInfo.getMissedPercent() + "‰");
    
            // 電量
            Cell cell7 = row.createCell(7);
            cell7.setCellValue(testInfo.getBatteryLevel());
    
            // 心率
            Cell cell8 = row.createCell(8);
            cell8.setCellValue(testInfo.getHRMax());
            Cell cell9 = row.createCell(9);
            cell9.setCellValue(testInfo.getHRMin());
    
            writeFile(mExcelWorkbook, path);
            return true;
        }

    生成的excel文件以及追加的數據

    這里寫圖片描述

    乍一看,這個excel表格中完全沒有格式。。。。都是jar包中默認的格式,主要原因在于createTitleCellStyle()函數中的mExcelWorkbook.createCellStyle();方法執行錯誤:

    NoSuchFileException:java.awt.Color

    通過查看poi.jar的源碼,得知,在HSSFColor類中,用到了java.awt.Color包:
    這里寫圖片描述

    而在android studio中編譯android代碼時,又不能引用java.awt.*包,所以這個問題。。我解決不了了。

    通過搜索資料,得知其實在eclipse中可以解決這個java.awt.*包的導入問題,因為我目前只是在做一個測試程序,所以沒有在eclipse上進行實踐,想通過這個方法解決這個問題的可以參考這篇博文:

    http://blog.csdn.net/du412983021/article/details/46602409

    ·jxl.jar

    在使用這個包的時候,本人偷了個懶,直接使用了別人已經封裝好的庫。

    https://github.com/zhouzhuo810/ZzExcelCreator

    簡單用該庫實現以下讀寫excel文件:

    import java.io.File;
    import java.io.IOException;
    
    import jxl.format.Alignment;
    import jxl.format.Colour;
    import jxl.format.VerticalAlignment;
    import jxl.read.biff.BiffException;
    import jxl.write.WritableCellFormat;
    import jxl.write.WritableFont;
    import jxl.write.WriteException;
    import me.zhouzhuo.zzexcelcreator.ZzExcelCreator;
    import me.zhouzhuo.zzexcelcreator.ZzFormatCreator;
    
    public class ExcelUtil {
    
        public static void writeExcel(String dir, String fileName, String testInfo) {
            try {
                initExcelWorkbook(dir, fileName);
                ZzExcelCreator.getInstance()
                        .openExcel(new File(dir, fileName + ".xls"))
                        .openSheet(0)
                        .fillContent(0, 2, testInfo, null)
                        .fillContent(1, 2, testInfo, null)
                        .fillContent(2, 2, testInfo, null)
                        .fillContent(3, 2, testInfo, null)
                        .close();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (WriteException e) {
                e.printStackTrace();
            } catch (BiffException e) {
                e.printStackTrace();
            }
    
    
        }
    
        public static void initExcelWorkbook(String dir, String fileName) throws IOException, WriteException {
            boolean flag;
            // 目標文件路徑
            File desSavedFileDir = new File(dir);
            // 目標文件
            File desSavedFile = new File(dir, fileName+".xls");
            flag = desSavedFileDir.isDirectory();
            if (!flag) {
                newExcel(dir, fileName);
            } else {
                if (!desSavedFile.exists()) {
                    newExcel(dir, fileName);
                }
            }
        }
    
        private static void newExcel(String dir, String fileName) throws IOException, WriteException {
            WritableCellFormat titleFormat = ZzFormatCreator
                    .getInstance()
                    .createCellFont(WritableFont.ARIAL)
                    .setAlignment(Alignment.CENTRE, VerticalAlignment.CENTRE)
                    .setFontSize(19)
                    .setFontColor(Colour.DARK_GREEN)
                    .getCellFormat();
            ZzExcelCreator
                    .getInstance()
                    .createExcel(dir, fileName)
                    .createSheet("jxl-test")
                    .fillContent(0, 0, "", titleFormat)
                    .fillContent(1, 0, "測試內容", titleFormat)
                    .merge(1, 0, 3, 0)
                    .fillContent(0, 1, "藍牙地址", titleFormat)
                    .fillContent(1, 1, "內容1", titleFormat)
                    .fillContent(2, 1, "內容2", titleFormat)
                    .fillContent(3, 1, "內容3", titleFormat)
                    .close();
        }
    }

    最終實現的結果如下:

    這里寫圖片描述

    但從代碼中看出,這個庫似乎并不能向excel文件中追加內容。所以如果你需要向已存在的excel文件中追加內容,還是使用原生的jxl.jar庫吧.

    try {
                initExcelWorkbook(dir, fileName);
    
                WritableWorkbook writableWorkbook = Workbook.createWorkbook(new File(dir, fileName + ".xls"));
                WritableSheet sheet = writableWorkbook.getSheet(0);
                int row = sheet.getRows();
                Label label = new Label(0, row + 1, "地址測試信息");
                sheet.addCell(label);
                Label label1 = new Label(1, row + 1, "測試1");
                sheet.addCell(label1);
                Label label2 = new Label(2, row + 1, "測試2");
                sheet.addCell(label2);
                Label label3 = new Label(3, row + 1, "測試3");
                sheet.addCell(label3);
                // 從內存中寫入文件中
                writableWorkbook.write();
                // 關閉資源,釋放內存
                writableWorkbook.close();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (WriteException e) {
                e.printStackTrace();
            }

    以上就是關于在android中,使用poi.jar和jxl.jar庫讀寫excel文件的介紹。

    版權聲明:本文為shangming150原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接和本聲明。
    本文鏈接:https://blog.csdn.net/shangming150/article/details/78261095

    智能推薦

    使用xlnt 讀寫excel文件

    環境 win10 64位 VS2017 64位 cmake 3.12.2 64位 1.生成空的項目 vs2017 文件->新建-->其他-->空項目-->ddxls(C:\Users\Administrator\source\repos\ddxls) 添加demo.cpp文件 項目-->右鍵-->添加新項 -->demo.cpp 2.給項目配置xlnt 3...

    JAVA 實現讀寫excel文件

    JAVA 實現讀寫excel文件 大家好,我是夢辛工作室的靈,最近在一個批量錄入數據的 工具,順便做了一下封裝,可以更好的使用: 使用方法如下: 結果如下: 下載地址:https://download.csdn.net/download/weixin_41392105/12657999...

    對Excel文件進行讀寫

    對Excel文件進行讀寫 相對來講,對Excel文件讀寫的情況較為復雜。首先我們要使用pip install openpyxl。然后我們還得稍微熟悉一下Excel文檔的基本概念 一個Excel文檔也稱為一個工作薄(workbook),每個工作薄里可以有多個工作表(wordsheet),當前打開的工作表又叫活動表。 每個工作表里有行和列,特定的行與列相交的方格稱為單元格(cell)。比如上圖第A列和...

    HTML中常用操作關于:頁面跳轉,空格

    1.頁面跳轉 2.空格的代替符...

    freemarker + ItextRender 根據模板生成PDF文件

    1. 制作模板 2. 獲取模板,并將所獲取的數據加載生成html文件 2. 生成PDF文件 其中由兩個地方需要注意,都是關于獲取文件路徑的問題,由于項目部署的時候是打包成jar包形式,所以在開發過程中時直接安照傳統的獲取方法沒有一點文件,但是當打包后部署,總是出錯。于是參考網上文章,先將文件讀出來到項目的臨時目錄下,然后再按正常方式加載該臨時文件; 還有一個問題至今沒有解決,就是關于生成PDF文件...

    猜你喜歡

    電腦空間不夠了?教你一個小秒招快速清理 Docker 占用的磁盤空間!

    Docker 很占用空間,每當我們運行容器、拉取鏡像、部署應用、構建自己的鏡像時,我們的磁盤空間會被大量占用。 如果你也被這個問題所困擾,咱們就一起看一下 Docker 是如何使用磁盤空間的,以及如何回收。 docker 占用的空間可以通過下面的命令查看: TYPE 列出了docker 使用磁盤的 4 種類型: Images:所有鏡像占用的空間,包括拉取下來的鏡像,和本地構建的。 Con...

    requests實現全自動PPT模板

    http://www.1ppt.com/moban/ 可以免費的下載PPT模板,當然如果要人工一個個下,還是挺麻煩的,我們可以利用requests輕松下載 訪問這個主頁,我們可以看到下面的樣式 點每一個PPT模板的圖片,我們可以進入到詳細的信息頁面,翻到下面,我們可以看到對應的下載地址 點擊這個下載的按鈕,我們便可以下載對應的PPT壓縮包 那我們就開始做吧 首先,查看網頁的源代碼,我們可以看到每一...

    Linux C系統編程-線程互斥鎖(四)

    互斥鎖 互斥鎖也是屬于線程之間處理同步互斥方式,有上鎖/解鎖兩種狀態。 互斥鎖函數接口 1)初始化互斥鎖 pthread_mutex_init() man 3 pthread_mutex_init (找不到的情況下首先 sudo apt-get install glibc-doc sudo apt-get install manpages-posix-dev) 動態初始化 int pthread_...

    統計學習方法 - 樸素貝葉斯

    引入問題:一機器在良好狀態生產合格產品幾率是 90%,在故障狀態生產合格產品幾率是 30%,機器良好的概率是 75%。若一日第一件產品是合格品,那么此日機器良好的概率是多少。 貝葉斯模型 生成模型與判別模型 判別模型,即要判斷這個東西到底是哪一類,也就是要求y,那就用給定的x去預測。 生成模型,是要生成一個模型,那就是誰根據什么生成了模型,誰就是類別y,根據的內容就是x 以上述例子,判斷一個生產出...

    精品国产乱码久久久久久蜜桃不卡