我正在尝试读取Excel文件。该文件保存在我的工作空间的名为RoCom_DB
的文件夹中,文件名为RoCom.xlsx
。
我正在尝试使用以下代码读取文件:
public String readComplexExcelFile(Context context){
try{
// Creating Input Stream
File file = new File(Environment.getExternalStorageDirectory()
+ "/Android/data/" + getApplicationContext().getPackageName()
+ "/RoCom_DB/", "RoCom.xlsx");
FileInputStream myInput = new FileInputStream(file);
// Create a POIFSFileSystem object
POIFSFileSystem myFileSystem = new POIFSFileSystem(myInput);
// Create a workbook using the File System
HSSFWorkbook myWorkBook = new HSSFWorkbook(myFileSystem);
// Get the first sheet from workbook
HSSFSheet mySheet = myWorkBook.getSheetAt(0);
/** We now need something to iterate through the cells.**/
Iterator<Row> rowIter = mySheet.rowIterator();
while(rowIter.hasNext()){
HSSFRow myRow = (HSSFRow) rowIter.next();
Iterator<Cell> cellIter = myRow.cellIterator();
while(cellIter.hasNext()){
HSSFCell myCell = (HSSFCell) cellIter.next();
Log.d("", "Cell Value: " + myCell.toString());
Toast.makeText(context, "cell Value: " + myCell.toString(), Toast.LENGTH_SHORT).show();
}
}
}catch (Exception e){
e.printStackTrace();
}
return "";
}
问题是每次我尝试读取文件时,都会得到一个
File not found exception
。我为此使用了必要的poi-3.7.jar
并将这段代码保留在我的manifest.xml
中:<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
我不想使用
assets
目录中的excel,因为它仅支持最大1 mb的excel,并且我的文件可能会增大。有人可以告诉我我做错了吗?任何帮助是极大的赞赏 。谢谢 。
最佳答案
我以一种非常奇怪的方式使它工作。 。
1>首先,我摆脱了POI.jar
,转而使用jxl.jar
。然后我的Excel工作簿再次采用xslx
格式,因为它是ms excel 2007,所以我将其转换为xls
即excel(97-2003)格式。
2>然后,我使用以下命令将excel推送到sdcard:
a>首先在cmd
中输入run
(对于Windows)
b>导航至您的adb.exe
所在的位置。(它将位于内部
android-> sdk->平台工具)
c>然后将您的xls复制到保存adb.exe的文件夹中。
d>现在运行adb shell。将打开unix外壳。转到:cd / mnt和
使用chmod 777 /sdcard
更改SD卡的许可
e>现在使用以下命令返回批处理提示:exit
命令并键入:adb push file.xls /mnt/sdcard/
f>然后使用/mnt/sdcard/
进入cd
并更改权限
对于使用以下文件的文件:chmod 777 file.xls
3>现在,所有重要的事情都完成了,我编写了以下代码来解决这个问题:
public String readComplexExcelFile(Context context, String userInput){
String requiredContents = "";
try{
File inputWorkbook = new File(Environment.getExternalStorageDirectory()+"/myFile.xls");
Workbook w;
// Create a workbook using the File System
w = Workbook.getWorkbook(inputWorkbook);
// Get the first sheet from workbook
Sheet sheet = w.getSheet(0);
/** We now need something to iterate through the cells.**/
for (int j = 0; j < sheet.getColumns(); j++) {
for (int i = 0; i < sheet.getRows(); i++) {
Cell cell = sheet.getCell(j, i);
if(cell.getContents().equalsIgnoreCase(userInput)){
Cell cellCorrespond = sheet.getCell(j+1, i);
requiredContents = cellCorrespond.getContents();
break;
}
}
}
}catch (Exception e){
e.printStackTrace();
}
return requiredContents;
}
希望这将帮助那些在同一过程中没有太多运气的人。干杯!