android read and write excel files

Android needs to use third-party jar files to operate excel files. There are two jar files that Android can use to operate excel files: poi.jar and jxl.jar. The main difference between the two is that poi.jar can operate excel before 2007, and jxl.jar can only operate on excel2003 and earlier. Next, we implement these two methods of reading and writing excel files.

·poi.jar

Download poi.jar package

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

There are many jar packages in the downloaded zip package. Since I did not use excel2007 here, I added poi-xxxx.jar to the project. If you need to use excel2007, add the jar package of poi-ooxml. Note: These two jar packages cannot be added at the same time, otherwise a duplicate error will be prompted.

Create a new excel file

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();
            }
        }
    }

The above code creates an excel file, adds a Sheet page named "mi-cms-test", adds some titles, and merges the cells of some titles. The content format of the generated excel file is as follows:
Write picture description here

Get the specified excel file

 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 工作簿对象
            }
        }
    }

Manipulate excel files and append data to excel files

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;
    }

Generated excel file and appended data

Write picture description here

At first glance, there is no formatting at all in this excel table. . . . They are all the default formats in the jar package. The main reason is that the method in the createTitleCellStyle() function has an execution error: mExcelWorkbook.createCellStyle();

NoSuchFileException:java.awt.Color

By looking at the source code of poi.jar, we learned that the java.awt.Color package is used in the HSSFColor class:
Write picture description here

When compiling android code in android studio, the java.awt.* package cannot be referenced, so this problem arises. . I can't solve it.

After searching for information, I learned that the problem of importing the java.awt.* package can be solved in eclipse. Because I am currently just making a test program, I have not practiced it on eclipse. If you want to solve this problem through this method, you can Refer to this blog post:

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

·jxl.jar

When using this package, I was lazy and directly used the library that others had packaged.

https://github.com/zhouzhuo810/ZzExcelCreator

Simply use this library to achieve the following reading and writing of excel files:

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();
    }
}

The final result is as follows:

Write picture description here

But from the code, it seems that this library cannot append content to excel files. So if you need to append content to an existing excel file, use the native jxl.jar library.

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();
        }

The above is an introduction to using the poi.jar and jxl.jar libraries to read and write excel files in Android.

Reprint: https://blog.csdn.net/shangming150/article/details/78261095

Guess you like

Origin blog.csdn.net/gqg_guan/article/details/134283986