Android開發中解析Excel (xls格式)教程

一,導入Jar包

二,ExcelBean

public class ExcelBean {
    private String number;

    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }
}

 

三,XlsDataUtil

public class XlsDataUtil {
    public static ArrayList getXlsData(final String xlsName, final int index, Context context){
        final ArrayList excelBeens = new ArrayList<>();
        final AssetManager assetManager = context.getAssets();
        try {
            Workbook workbook = Workbook.getWorkbook(assetManager.open(xlsName));
            Sheet sheet = workbook.getSheet(index);
            int sheetNum = workbook.getNumberOfSheets();
            //行
            int sheetRows = sheet.getRows();
            //列
            int sheetColumns = sheet.getColumns();
            for (int i = 0; i < sheetRows; i++) {
                ExcelBean excelBean = new ExcelBean();
                excelBean.setNumber(sheet.getCell(0,i).getContents()+"");
                excelBeens.add(excelBean);
            }
            workbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (BiffException e) {
            e.printStackTrace();
        }
        return excelBeens;
    }
}

三,MainActivity 佈局




    

 

四,MainActivity

public class MainActivity extends AppCompatActivity {

    private TextView tv;
    private Handler handler;
    private ArrayList data;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tv = (TextView) findViewById(R.id.tv);
        data = new ArrayList<>();
        //更新UI
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                int i = (int) msg.obj;
                if (i == 1) {
                    String s = "";
                    for (int i1 = 0; i1 < data.size(); i1++) {
                        s+= data.get(i1).getNumber();
                    }
                    tv.setText(s);
                }
            }
        };

        //解析耗時  放到子線程裡面
        new Thread(new Runnable() {
            @Override
            public void run() {
                data.addAll(XlsDataUtil.getXlsData("android_text.xls" , 0 , MainActivity.this));
                Message message = handler.obtainMessage();
                message.obj = 1;
                handler.sendMessage(message);
            }
        }).start();


    }


}

You May Also Like