Office文档是以二进制格式存储的,对于它的读写不能像普通文本一样通过File来操作,如果以二进制格式读取到内存中,我们也是不能够正确解析其中的内容的,在Windows开发中、或者使用QT开发中,我们可以使用库提供的控件或者API来操作Office文档,但是在Android系统开发中,Android本身并没有提供这样的一套API。所以我们需要借用开源的一些库,本文根据项目中的使用需求,项目中使用了Apache POI来读写Office文档,把使用的一些套路、方法和趟过的坑记录整理出来,方便有同样需求的朋友参考。
Apache POI
Apache POI是Apache 的一个开源项目,是一个JAVA项目,下载地址:http://poi.apache.org/download.html,API文档:http://poi.apache.org/apidocs/index.html。Apache POI设计的目的是方便Java程序创建、读取、写入Office文档。
Android 项目中使用Apache POI
方法1. 下载JAR包,应用
1. 从官网下载Binary Distribution包,像导入其它java包一样,将下载的包放到Android Studio 工程的libs目录下,并在项目中根据需要导入jar包,可以在工程里通过图形化的界面导入,也可以直接在build.gradle中添加依赖,依赖根据自己需要使用的库添加,官网上有依赖关系,可以对应查找,,比如在我的测试项目中:
2.编译中如果出现如下问题:java.lang.NoSuchMethodError: No static method metafactory(Ljava/lang/invoke/..., 请配置java版本到VERSION_1_8,如下:
compileOptions{
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
方法2. gradle依赖
build.gradle文件中加入如下依赖,处理doc xls ppt,但不能处理docx,xlsx,pptx implementation 'org.apache.poi:poi-scratchpad:4.1.2'
对于docx,xlsx,pptx的处理,在Android上POI由于依赖问题不能正常使用,网上有一些解决方案,但本人试验未成功。本人对docx,xlsx,pptx的简单处理方式是自行解析。
示例代码:
创建
public class Excel {
private static final String TAG = "Execl";
private static final String[] CONTENT = new String[] {"one", "two", "three", "four", "five", "six",
"seven", "eight", "nine", "ten"};
private static final String FILENAME = "textExcel.xls";
public void exportExcelFile(FileOutputStream fos) {
int size = 10;
Workbook wb = new HSSFWorkbook();
Sheet sh = wb.createSheet();
for (int rownum = 0; rownum < size; rownum++) {
Row row = sh.createRow(rownum);
for (int cellnum = 0; cellnum < size; cellnum++) {
Cell cell = row.createCell(cellnum);
cell.setCellValue(CONTENT[cellnum]);
}
}
try {
wb.write(fos);
fos.close();
Log.d(TAG, "导出成功");
} catch (IOException e) {
e.printStackTrace();
}
}
public StringBuffer importExcelFile(FileInputStream fis) {
StringBuffer buf = new StringBuffer();
try {
POIFSFileSystem fs = new POIFSFileSystem(fis);
HSSFWorkbook wk = new HSSFWorkbook(fs);
HSSFSheet sheet = wk.getSheetAt(0);
for (Row row : sheet) {
for (Cell cell : row) {
CellType cellType = cell.getCellType();
if (cellType == CellType.BLANK) {
buf.append("\t");
} else if (cellType == CellType.NUMERIC) {
buf.append(cell.getNumericCellValue())
.append("\t");
} else if (cellType == CellType.STRING) {
buf.append(cell.getStringCellValue())
.append("\t");
}
}
buf.append("\n");
}
} catch (IOException e) {
e.printStackTrace();
}
return buf;
}
}