Home Java javaTutorial How to operate Excel files using Android

How to operate Excel files using Android

Mar 09, 2017 pm 06:54 PM

This article introduces how to use Android to operate Excel files

When operating Excel files and exporting reports in Android, the open source library jxl is mainly used. It was first used on java, but it can also be used on Android. Similar POI can only be used for Java, not Android, because it relies on many libraries.

To use jxl, you need to import the jxl.jar package in the Android project. jxl can complete the basic reading and writing operations of Excel. Its support and non-support are as follows:
1. jxl only supports Excel2003 format, not Support Excel2007 format. That is, xls files are supported, but xlsx files are not supported.
2. jxl does not support direct modification of excel files, but it can be modified indirectly by copying a new file and overwriting the original file.
3. jxl can only recognize images in PNG format and cannot recognize images in other formats.


As can be seen from the above, jxl does not support Excel2007, which is very bad, especially when Excel2007 has become the mainstream Excel format. However, there is now a temporary method for Android to read the 2007 format. If we carefully analyze the file format of xlsx, we will find that the xlsx file is actually a compressed package. There are various files in the compressed package, and the data is generally placed in "xl/ sharedStrings.xml" and "xl/worksheets/sheet1.xml". Based on this, when we determine that the Excel file is in 2007 format, we can decompress it, extract sharedStrings.xml and sheet1.xml from it, and then use XML parsing tools to parse out the specific data.


The following is an example of reading and writing code for Excel files, which supports reading and writing in 2003 format, as well as reading in 2007 format:

import java.io.File;  
import java.io.IOException;  
import java.io.InputStream;  
import java.util.ArrayList;  
import java.util.List;  
import java.util.zip.ZipEntry;  
import java.util.zip.ZipException;  
import java.util.zip.ZipFile;  
  
import org.xmlpull.v1.XmlPullParser;  
import org.xmlpull.v1.XmlPullParserException;  
  
import android.util.Log;  
import android.util.Xml;  
  
import jxl.Sheet;  
import jxl.Workbook;  
import jxl.write.Label;  
import jxl.write.WritableSheet;  
import jxl.write.WritableWorkbook;  
  
public class ExcelUtil {  
    private final static String TAG = "ExcelUtil";  
  
    public static List<List<Object>> read(String file_name) {  
        String extension = file_name.lastIndexOf(".") == -1 ? "" : file_name  
                .substring(file_name.lastIndexOf(".") + 1);  
        if ("xls".equals(extension)) {// 2003  
            Log.d(TAG, "read2003XLS, extension:" + extension);  
            return read2003XLS(file_name);  
        } else if ("xlsx".equals(extension)) {  
            Log.d(TAG, "read2007XLSX, extension:" + extension);  
            return read2007XLSX(file_name);  
        } else {  
            Log.d(TAG, "不支持的文件类型, extension:" + extension);  
            return null;  
        }  
    }  
  
    public static List<List<Object>> read2003XLS(String path) {  
        List<List<Object>> dataList = new ArrayList<List<Object>>();  
        try {  
            Workbook book = Workbook.getWorkbook(new File(path));  
            // book.getNumberOfSheets();  //获取sheet页的数目  
            // 获得第一个工作表对象  
            Sheet sheet = book.getSheet(0);  
            int Rows = sheet.getRows();  
            int Cols = sheet.getColumns();  
            Log.d(TAG, "当前工作表的名字:" + sheet.getName());  
            Log.d(TAG, "总行数:" + Rows + ", 总列数:" + Cols);  
  
            List<Object> objList = new ArrayList<Object>();  
            String val = null;  
            for (int i = 0; i < Rows; i++) {  
                boolean null_row = true;  
                for (int j = 0; j < Cols; j++) {  
                    // getCell(Col,Row)获得单元格的值,注意getCell格式是先列后行,不是常见的先行后列  
                    Log.d(TAG, (sheet.getCell(j, i)).getContents() + "\t");  
                    val = (sheet.getCell(j, i)).getContents();  
                    if (val == null || val.equals("")) {  
                        val = "null";  
                    } else {  
                        null_row = false;  
                    }  
                    objList.add(val);  
                }  
                Log.d(TAG, "\n");  
                if (null_row != true) {  
                    dataList.add(objList);  
                    null_row = true;  
                }  
                objList = new ArrayList<Object>();  
            }  
            book.close();  
        } catch (Exception e) {  
            Log.d(TAG, e.getMessage());  
        }  
  
        return dataList;  
    }  
  
    public static List<List<Object>> read2007XLSX(String path) {  
        List<List<Object>> dataList = new ArrayList<List<Object>>();  
        String str_c = "";  
        String v = null;  
        boolean flat = false;  
        List<String> ls = new ArrayList<String>();  
        try {  
            ZipFile xlsxFile = new ZipFile(new File(path));  
            ZipEntry sharedStringXML = xlsxFile.getEntry("xl/sharedStrings.xml");  
            if (sharedStringXML == null) {  
                Log.d(TAG, "空文件:" + path);  
                return dataList;  
            }  
            InputStream inputStream = xlsxFile.getInputStream(sharedStringXML);  
            XmlPullParser xmlParser = Xml.newPullParser();  
            xmlParser.setInput(inputStream, "utf-8");  
            int evtType = xmlParser.getEventType();  
            while (evtType != XmlPullParser.END_DOCUMENT) {  
                switch (evtType) {  
                case XmlPullParser.START_TAG:  
                    String tag = xmlParser.getName();  
                    if (tag.equalsIgnoreCase("t")) {  
                        ls.add(xmlParser.nextText());  
                    }  
                    break;  
                case XmlPullParser.END_TAG:  
                    break;  
                default:  
                    break;  
                }  
                evtType = xmlParser.next();  
            }  
            ZipEntry sheetXML = xlsxFile.getEntry("xl/worksheets/sheet1.xml");  
            InputStream inputStreamsheet = xlsxFile.getInputStream(sheetXML);  
            XmlPullParser xmlParsersheet = Xml.newPullParser();  
            xmlParsersheet.setInput(inputStreamsheet, "utf-8");  
            int evtTypesheet = xmlParsersheet.getEventType();  
            List<Object> objList = new ArrayList<Object>();  
            String val = null;  
            boolean null_row = true;  
  
            while (evtTypesheet != XmlPullParser.END_DOCUMENT) {  
                switch (evtTypesheet) {  
                case XmlPullParser.START_TAG:  
                    String tag = xmlParsersheet.getName();  
                    if (tag.equalsIgnoreCase("row")) {  
                    } else if (tag.equalsIgnoreCase("c")) {  
                        String t = xmlParsersheet.getAttributeValue(null, "t");  
                        if (t != null) {  
                            flat = true; // 字符串型  
                            // Log.d(TAG, flat + "有");  
                        } else { // 非字符串型,可能是整型  
                            // Log.d(TAG, flat + "没有");  
                            flat = false;  
                        }  
                    } else if (tag.equalsIgnoreCase("v")) {  
                        v = xmlParsersheet.nextText();  
                        if (v != null) {  
                            if (flat) {  
                                str_c += ls.get(Integer.parseInt(v)) + "  ";  
                                val = ls.get(Integer.parseInt(v));  
                                null_row = false;  
                            } else {  
                                str_c += v + "  ";  
                                val = v;  
                            }  
                            objList.add(val);  
                        }  
                    }  
                    break;  
                case XmlPullParser.END_TAG:  
                    if (xmlParsersheet.getName().equalsIgnoreCase("row") && v != null) {  
                        str_c += "\n";  
                        if (null_row != true) {  
                            dataList.add(objList);  
                            null_row = true;  
                        }  
                        objList = new ArrayList<Object>();  
                    }  
                    break;  
                }  
                evtTypesheet = xmlParsersheet.next();  
            }  
            Log.d(TAG, str_c);  
        } catch (ZipException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        } catch (XmlPullParserException e) {  
            e.printStackTrace();  
        }  
        if (str_c == null) {  
            str_c = "解析文件出现问题";  
            Log.d(TAG, str_c);  
        }  
  
        return dataList;  
    }  
  
    public static int writeExcel(String file_name, List<List<Object>> data_list) {  
        try {  
            WritableWorkbook book = Workbook.createWorkbook(new File(file_name));  
            WritableSheet sheet1 = book.createSheet("sheet1", 0);  
            for (int i = 0; i < data_list.size(); i++) {  
                List<Object> obj_list = data_list.get(i);  
                for (int j = 0; j < obj_list.size(); j++) {  
                    Label label = new Label(j, i, obj_list.get(j).toString());  
                    sheet1.addCell(label);  
                }  
            }  
            book.write();  
            book.close();  
        } catch (Exception e) {  
            e.printStackTrace();  
            return -1;  
        }  
        return 0;  
    }
Copy after login

 

The above is the detailed content of How to operate Excel files using Android. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1655
14
PHP Tutorial
1252
29
C# Tutorial
1226
24
Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list? How to use the Redis cache solution to efficiently realize the requirements of product ranking list? Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

See all articles