Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 教學:用 JXL 解析 Excel 檔案

編輯:關於 Android 程式設計

除了 Apache POI,另一個常見的選擇是 JXL(jxl.jar)。以下示範如何用它讀取 Excel 文件。

MainActivity 如下:

package cc.testexcel;
import java.io.File;
import jxl.Cell;
import jxl.CellType;
import jxl.DateCell;
import jxl.NumberCell;
import jxl.Sheet;
import jxl.Workbook;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;

/**
 * Demo 描述:利用 jxl.jar 解析 Excel 文件
 *
 * 注意事項:
 * 1. 讀取每個儲存格時,要留意其型別(CellType),
 *    這樣才能對不同型別區分處理。
 * 2. 測試用的 Excel 文件放在 assets 資料夾下。
 */
public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        parseExcel();
    }

    private void parseExcel() {
        try {
            Workbook workbook = null;
            try {
                File file = new File(Environment.getExternalStorageDirectory()
                        + File.separator + "test.xls");
                workbook = Workbook.getWorkbook(file);
            } catch (Exception e) {
                throw new Exception("File not found");
            }
            // 取得第一張表
            Sheet sheet = workbook.getSheet(0);
            // 列數
            int columnCount = sheet.getColumns();
            // 行數
            int rowCount = sheet.getRows();
            // 儲存格
            Cell cell = null;
            for (int everyRow = 0; everyRow < rowCount; everyRow++) {
                for (int everyColumn = 0; everyColumn < columnCount; everyColumn++) {
                    cell = sheet.getCell(everyColumn, everyRow);
                    if (cell.getType() == CellType.NUMBER) {
                        System.out.println("數字=" + ((NumberCell) cell).getValue());
                    } else if (cell.getType() == CellType.DATE) {
                        System.out.println("時間=" + ((DateCell) cell).getDate());
                    } else {
                        System.out.println("everyColumn=" + everyColumn
                                + ",everyRow=" + everyRow
                                + ",cell.getContents()=" + cell.getContents());
                    }
                }
            }
            // 關閉 workbook,防止記憶體洩漏
            workbook.close();
        } catch (Exception e) {
        }
    }
}

main.xml 如下:


    

關鍵在於:讀取每個儲存格前先判斷 CellType,就能針對數字、日期、文字等不同型別分別處理,最後別忘了呼叫 workbook.close() 釋放資源。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved