android读写excel文件

来源:互联网 发布:琉璃神社新的域名 编辑:程序博客网 时间:2024/06/07 13:27

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文件的介绍。

原创粉丝点击