Detailed explanation of reading Excel file instances in Android
Recently, there was a requirement to build data in the app. I threw the new product at two Excel tables and ignored it (the formats of the two tables are not unified...). So I found a way to read Excel table files in Android through Baidu and other methods, and record them.
Let’s talk about the difference between workbooks and worksheets in Excel:
The workbook contains worksheets. A workbook can be composed of one or more worksheets, and a workbook is an EXCEL table file.
OK, start reading the form file.
premise
First, let's assume that the name of the table file to be read is located in the assets root directory.
Required Jar Package
In order to be able to read Excel table files here, we need to add a third-party Jar package jxl.
There are some things to note here: Since there are many table file formats, the old version of jxl only supports Excel2003 version, so if the table file format obtained is xlsm or xlsn, we must first save the file as xls format.
Start reading
1. Initialize variables:
InputStream inputStream = null;//Input StreamFileOutputStream outputStream = null;//Output StreamWorkbook book = null;//Excel workbook object
2. Read the table file we built in the assets directory in the stream
inputStream = ().open("");
3. Read the input stream from the previous step into a file for easier subsequent use
File tempFile = new File((), "");//Temporary file, the second parameter is the file name, you can get it at willoutputStream = new FileOutputStream(tempFile); byte[] buf = new byte[1024]; int len; while ((len = (buf)) > 0) {// while loop for reading(buf, 0, len); } (); ();
4. After obtaining the Excel file object, you can use the various methods provided in the jxl package to operate the table file. There are many methods provided by jxl, here is a brief introduction to several used in the project.
book = Workbook .getWorkbook(tempFile);//Use the read table file to instantiate the workbook object (as common sense, what we want to operate is the Excel workbook file)Sheet[] sheets = (); //Get all worksheetsfor (int m = 0; m < ; m++) { Sheet sheet = (m); int Rows = ();//Get the number of rows in the current worksheetint Cols = (); //Get the number of columns in the current worksheetfor (int i = 0; i < Cols; i++) { // Note: This is read by column! ! !for (int j = 0; j < Rows; j++) { String content=(i, j).getContents();//The result is of type String, type conversion is performed according to specific requirements } } }
Summarize
If the table file is built in the assets directory, you can read it according to the above process. If it is on an SD card or something, the steps are basically the same. We first get our table file, then get the workbook object, and operate it.
Thank you for reading, I hope it can help you. Thank you for your support for this site!