android读取xlsx文件封装,android读取assets中Excel表格并显示
时间: 2024-01-17 16:05:57 浏览: 168
Android应用源码之安卓读取Excel文件获取表格数据.zip
要读取XLSX文件,可以使用Apache POI库。以下是一个简单的封装类,可以读取Assets文件夹中的XLSX文件并将其显示在Android应用程序中:
```java
import android.content.Context;
import android.content.res.AssetManager;
import android.util.Log;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
public class ExcelReader {
private static final String TAG = ExcelReader.class.getSimpleName();
public static ArrayList<ArrayList<String>> readExcel(Context context, String fileName) {
ArrayList<ArrayList<String>> dataList = new ArrayList<>();
AssetManager assetManager = context.getAssets();
try {
InputStream inputStream = assetManager.open(fileName);
XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
Sheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
ArrayList<String> rowData = new ArrayList<>();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
String cellValue = "";
switch (cell.getCellType()) {
case STRING:
cellValue = cell.getStringCellValue();
break;
case NUMERIC:
cellValue = String.valueOf(cell.getNumericCellValue());
break;
case BOOLEAN:
cellValue = String.valueOf(cell.getBooleanCellValue());
break;
default:
break;
}
rowData.add(cellValue);
}
dataList.add(rowData);
}
} catch (IOException e) {
Log.e(TAG, "readExcel: ", e);
}
return dataList;
}
}
```
然后,在您的Activity或Fragment中,您可以像这样使用它:
```java
ArrayList<ArrayList<String>> dataList = ExcelReader.readExcel(getContext(), "example.xlsx");
for (ArrayList<String> row : dataList) {
for (String cell : row) {
Log.d(TAG, cell);
}
}
```
请注意,在这个例子中,我们假设您的XLSX文件只有一个工作表,并且该工作表是第一个工作表。如果您的文件包含多个工作表,您需要根据需要更改代码。
阅读全文