4
我編寫了這段代碼來讀取我將它粘貼到資產文件夾(我的文件名:book.xls)中的Excel文件來讀取它。但是當我按下按鈕來顯示文件它不起作用,並沒有顯示任何東西。 請幫我解決我的問題。 非常感謝。 這裏是我的代碼:在android.java中讀取Excel文件
package com.example.android.readingexcellfile;
import android.content.res.AssetManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import java.io.InputStream;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void order (View v){
try
{
AssetManager am=getAssets();
InputStream is=am.open("book.xls");
Workbook wb=Workbook.getWorkbook(is);
Sheet s=wb.getSheet(0);
int row=s.getRows();
int col=s.getColumns();
String xx="";
for (int i=0;i<row;i++)
{
for(int c=0;i<col;c++)
{
Cell z=s.getCell(c,i);
xx=xx+z.getContents();
}
xx=xx+"\n";
}
display(xx);
}
catch (Exception e){}
}
public void display (String value){
TextView x=(TextView)findViewById(R.id.textView);
x.setText(value);
}
}
這裏是我的xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.android.readingexcellfile.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:id="@+id/textView" />
<Button
android:text="Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="28dp"
android:layout_marginStart="28dp"
android:layout_marginTop="69dp"
android:onClick="order"
android:id="@+id/button" />
</RelativeLayout>
一旦你解決了這個問題,你應該考慮的下一件事是「爲什麼一個Excel文件」? 鑑於該文件已嵌入資產文件夾中,並且用戶無法對其進行更改,爲何不將其轉換爲更友好的格式,如.csv文件,甚至可以使用Java創建一個數據類這個數據? 然後,通過省略Excel文件和Jexcel庫,你的APK會變得更小。 – GreyBeardedGeek