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

Android 端把 SQLite 資料匯出成 Excel:JXL 完整實作指南

編輯:關於 Android 程式設計

做過 Java Web 或 C# 的朋友,對 POI 這套元件應該不陌生,尤其在 OA 類專案裡,Excel 的匯入與匯出幾乎是標配。那麼在 Android App 上能不能做類似的事?本文就以一個小記帳工具為例,說明如何把寫在 EditText 裡的資料先落進 SQLite,再一鍵匯出成 Excel 檔案。

為什麼選 JXL

要在 Android 上操作 Excel,第一步是把 JXL 這個第三方庫引入專案。

JXL 是一個開源的 Java Excel API 專案,讓 Java 程式能相當方便地讀寫微軟 Excel 文件。除了 JXL,Apache 的 POI 也能勝任同樣的工作,兩者的取捨大致如下:JXL 上手快、API 直覺,缺點是功能相對單薄;POI 功能強大但學習曲線陡,用在簡單場景反而顯得笨重。如果只是把資料寫成一份報表,JXL 綽綽有餘。

核心 API 速覽

1. 建立或讀取工作簿(Workbook)

工作簿代表整份 Excel 文件:

WritableWorkbook wwb = Workbook.createWorkbook(os);

其中 os 是一個檔案輸出流,當然也可以直接傳入 File 物件。Workbook 不只負責建立,也能讀取既有檔案:

Workbook.getWorkbook(java.io.File file);

Workbook 幾乎是整個 JXL 的中樞,方法多為 static,呼叫起來相當省事。

2. 建立工作表(Sheet)

工作表由 WritableWorkbook 產生,方法為 createSheet(name, index),兩個參數分別是表名與插入位置(從 0 起算):

WritableSheet sheet = wwb.createSheet("家庭帳務表", 0);

3. 建立標籤(Label)

這裡所說的標籤,其實就是工作表裡的儲存格。儲存格有多種型別,分別對應不同類別,例如 jxl.write.Boolean、jxl.write.Number 等:

Label label = new Label(col, row, title);

三個參數分別代表第 col+1 列、第 row+1 列,以及內容 title。建立好之後要記得加入工作表:

sheet.addCell(label);

4. 填充各種類型的資料

資料填充稍微複雜一些,牽涉到儲存格格式。

填充數字:

jxl.write.Number numb = new jxl.write.Number(1, 1, 250);
sheet.addCell(numb);

填充帶格式的數字:

jxl.write.NumberFormat nf = new jxl.write.NumberFormat("#.##");
jxl.write.WritableCellFormat wcf = new jxl.write.WritableCellFormat(nf);
jxl.write.Number n = new jxl.write.Number(2, 1, 2.451, wcf);
sheet.addCell(n);

填充日期:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String newdate = sdf.format(new Date());
label = new Label(2, 2, newdate);
sheet.addCell(label);

填充文字:

label = new Label(3, 3, "周星馳");
sheet.addCell(label);

填充布林值:

jxl.write.Boolean bool = new jxl.write.Boolean(4, 1, true);
sheet.addCell(bool);

5. 合併儲存格

透過 mergeCells(x, y, m, n) 完成,代表把第 x+1 列、y+1 行至第 m+1 列、n+1 行合併,四個參數定義了左上角與右下角兩個座標,合併的格子數量即兩軸跨距的乘積。

sheet.mergeCells(0, 6, 3, 8);
label = new Label(0, 6, "合併了12個儲存格");
sheet.addCell(label);

6. 設定儲存格樣式

主要用來調整背景、框線、對齊等:

WritableCellFormat wc = new WritableCellFormat();
wc.setAlignment(Alignment.CENTRE);              // 置中
wc.setBorder(Border.ALL, BorderLineStyle.THIN); // 加上框線
wc.setBackground(jxl.format.Colour.RED);        // 背景色
label = new Label(1, 5, "字體", wc);
sheet.addCell(label);

7. 設定字型

jxl.write.WritableFont wfont = new jxl.write.WritableFont(WritableFont.createFont("楷書"), 20);
WritableCellFormat font = new WritableCellFormat(wfont);
label = new Label(2, 6, "楷書", font);
sheet.addCell(label);

8. 寫入並關閉檔案

wwb.write();  // 寫入資料
wwb.close();  // 關閉檔案

9. 列與行的批次操作

jxl.write.WritableSheet[] sheetList = wwb.getSheets(); // 取得所有工作表
jxl.Cell[] cellc = sheet.getColumn(0);                // 第 1 列所有儲存格
jxl.Cell[] cellr = sheet.getRow(0);                   // 第 1 行所有儲存格
Cell c = sheet.getCell(0, 0);                         // 左上角儲存格

10. 讀取儲存格內容

String value = c.getContents(); // 不論型別,一律回傳字串

實作:小記帳工具的資料層

API 熟悉之後,重點就落在怎麼把 App 的資料整理好餵給 Excel。先看資料庫的部分:

public class DBHelper extends SQLiteOpenHelper {
    public static final String DB_NAME = "ldm_family"; // 資料庫名稱

    private Context mcontext;
    private DBHelper mDbHelper;
    private SQLiteDatabase db;

    public DBHelper(Context context) {
        super(context, DB_NAME, null, 11);
        this.mcontext = context;
    }

    public DBHelper(Context context, String name, CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

    /** 首次安裝時建立資料表 */
    @Override
    public void onCreate(SQLiteDatabase db) {
        String sql = "create table if not exists family_bill(id integer primary key,time text,food text,use text,traffic text,travel text,clothes text,doctor text,laiwang text,baby text,live text,other text,remark text)";
        db.execSQL(sql);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { }

    /** 開啟資料庫,已開啟則直接沿用 */
    public DBHelper open() {
        if (null == mDbHelper) {
            mDbHelper = new DBHelper(mcontext);
        }
        db = mDbHelper.getWritableDatabase();
        return this;
    }

    public void close() {
        db.close();
        mDbHelper.close();
    }

    /** 新增資料 */
    public long insert(String tableName, ContentValues values) {
        return db.insert(tableName, null, values);
    }

    /** 查詢資料 */
    public Cursor findList(String tableName, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit) {
        return db.query(tableName, columns, selection, selectionArgs, groupBy, having, orderBy, limit);
    }

    public Cursor exeSql(String sql) {
        return db.rawQuery(sql, null);
    }
}

主介面這邊放上一排 EditText,讓使用者逐項填入當日支出,按下按鈕後存入資料庫:

public class MainActivity extends Activity implements OnClickListener {
    private EditText mFoodEdt;
    private EditText mArticlesEdt;
    private EditText mTrafficEdt;
    private EditText mTravelEdt;
    private EditText mClothesEdt;
    private EditText mDoctorEdt;
    private EditText mRenQingEdt;
    private EditText mBabyEdt;
    private EditText mLiveEdt;
    private EditText mOtherEdt;
    private EditText mRemarkEdt;
    private Button mSaveBtn;

    private String[] title = { "日期", "食物支出", "大保健費", "交通話費", "旅遊出行", "穿著支出",
                               "醫療保健", "人情往來", "寶寶專項", "房租水電", "其它支出", "備註說明" };

    private String[] saveData;
    private DBHelper mDbHelper;
    private ArrayList<Map<String, String>> bill2List;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewsById();
        mDbHelper = new DBHelper(this);
        mDbHelper.open();
        bill2List = new ArrayList<Map<String, String>>();
    }

    /** 宣告各元件 */
    private void findViewsById() {
        mFoodEdt    = (EditText) findViewById(R.id.family_bill_food_edt);
        mArticlesEdt= (EditText) findViewById(R.id.family_bill_articles_edt);
        mTrafficEdt = (EditText) findViewById(R.id.family_bill_traffic_edt);
        mTravelEdt  = (EditText) findViewById(R.id.family_bill_travel_edt);
        mClothesEdt = (EditText) findViewById(R.id.family_bill_clothes_edt);
        mDoctorEdt  = (EditText) findViewById(R.id.family_bill_doctor_edt);
        mRenQingEdt = (EditText) findViewById(R.id.family_bill_laiwang_edt);
        mBabyEdt    = (EditText) findViewById(R.id.family_bill_baby_edt);
        mLiveEdt    = (EditText) findViewById(R.id.family_bill_live_edt);
        mOtherEdt   = (EditText) findViewById(R.id.family_bill_other_edt);
        mRemarkEdt  = (EditText) findViewById(R.id.family_bill_remark_edt);
        mSaveBtn    = (Button)   findViewById(R.id.family_bill_save);
        mSaveBtn.setOnClickListener(this);
    }
    // onClick 中負責收集欄位、寫入 SQLite,並呼叫匯出邏輯
}

實作:Excel 產生器

CreateExcel 負責建立活頁簿、寫入標題列,並把每一筆紀錄逐列填進去:

public class CreateExcel {
    private WritableSheet sheet;      // 工作表
    private WritableWorkbook wwb;     // 活頁簿

    private String[] title = { "日期", "食物支出", "大保健費", "交通話費", "旅遊出行", "穿著支出",
                               "醫療保健", "人情往來", "寶寶專項", "房租水電", "其它支出", "備註說明" };

    public CreateExcel() { excelCreate(); }

    /** 建立 Excel 活頁簿 */
    public void excelCreate() {
        try {
            /** 輸出的 Excel 檔案路徑 */
            String filePath = Environment.getExternalStorageDirectory() + "/family_bill";
            File file = new File(filePath, "bill.xls");
            if (!file.exists()) {
                file.createNewFile();
            }
            wwb = Workbook.createWorkbook(file);
            /** 新增第一個工作表並命名 */
            sheet = wwb.createSheet("家庭帳務表", 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void saveDataToExcel(int index, String[] content) throws Exception {
        Label label;
        for (int i = 0; i < title.length; i++) {
            /** Label(x,y,z):x 代表第 x+1 列,y 代表第 y+1 行,z 為內容 */
            label = new Label(i, 0, title[i]);
            sheet.addCell(label);
        }
        /* 把資料逐格填入,注意路徑必須使用完整路徑,否則容易出錯 */
        for (int i = 0; i < title.length; i++) {
            Label labeli = new Label(i, index, content[i]);
            sheet.addCell(labeli);
        }
        wwb.write();  // 寫入資料
        wwb.close();  // 關閉檔案
    }
}

若希望報表好看一點,可以另外抽一個工具類統一管理字型與樣式:

public class ExcelUtils {
    public static WritableFont arial14font = null;
    public static WritableCellFormat arial14format = null;
    public static WritableFont arial10font = null;
    public static WritableCellFormat arial10format = null;
    public static WritableFont arial12font = null;
    public static WritableCellFormat arial12format = null;

    public final static String UTF8_ENCODING = "UTF-8";
    public final static String GBK_ENCODING  = "GBK";

    /** 預先準備好幾種樣式,避免重複建立 */
    public static void format() {
        try {
            arial14font = new WritableFont(WritableFont.ARIAL, 14, WritableFont.BOLD);
            arial14font.setColour(jxl.format.Colour.LIGHT_BLUE);
            arial14format = new WritableCellFormat(arial14font);
            arial14format.setAlignment(jxl.format.Alignment.CENTRE);
            arial14format.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);
            arial14format.setBackground(jxl.format.Colour.VERY_LIGHT_YELLOW);

            arial10font = new WritableFont(WritableFont.ARIAL, 10, WritableFont.BOLD);
            arial10format = new WritableCellFormat(arial10font);
            arial10format.setAlignment(jxl.format.Alignment.CENTRE);
            arial10format.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);
            arial10format.setBackground(jxl.format.Colour.LIGHT_BLUE);

            arial12font = new WritableFont(WritableFont.ARIAL, 12);
            arial12format = new WritableCellFormat(arial12font);
            arial12format.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);
        } catch (WriteException e) {
            e.printStackTrace();
        }
    }

    /** 建立帶標題列的空白表格 */
    public static void initExcel(String fileName, String[] colName) {
        format();
        WritableWorkbook workbook = null;
        try {
            File file = new File(fileName);
            if (!file.exists()) {
                file.createNewFile();
            }
            workbook = Workbook.createWorkbook(file);
            WritableSheet sheet = workbook.createSheet("家庭帳務表", 0);
            sheet.addCell((WritableCell) new Label(0, 0, fileName, arial14format));
            for (int col = 0; col < colName.length; col++) {
                sheet.addCell(new Label(col, 0, colName[col], arial10format));
            }
            workbook.write();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (workbook != null) {
                try { workbook.close(); } catch (Exception e) { e.printStackTrace(); }
            }
        }
    }

    /** 把一組字串列表寫進既有檔案 */
    @SuppressWarnings("unchecked")
    public static <T> void writeObjListToExcel(List<T> objList, String fileName, Context c) {
        if (objList != null && objList.size() > 0) {
            WritableWorkbook writebook = null;
            InputStream in = null;
            try {
                WorkbookSettings setEncode = new WorkbookSettings();
                setEncode.setEncoding(UTF8_ENCODING);
                in = new FileInputStream(new File(fileName));
                Workbook workbook = Workbook.getWorkbook(in);
                writebook = Workbook.createWorkbook(new File(fileName), workbook);
                WritableSheet sheet = writebook.getSheet(0);
                for (int j = 0; j < objList.size(); j++) {
                    ArrayList<String> list = (ArrayList<String>) objList.get(j);
                    for (int i = 0; i < list.size(); i++) {
                        sheet.addCell(new Label(i, j + 1, list.get(i), arial12format));
                    }
                }
                writebook.write();
                Toast.makeText(c, "儲存成功", Toast.LENGTH_SHORT).show();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (writebook != null) {
                    try { writebook.close(); } catch (Exception e) { e.printStackTrace(); }
                }
                if (in != null) {
                    try { in.close(); } catch (IOException e) { e.printStackTrace(); }
                }
            }
        }
    }

    /** 以 getter 反射取值的小工具 */
    public static Object getValueByRef(Class cls, String fieldName) {
        Object value = null;
        fieldName = fieldName.replaceFirst(fieldName.substring(0, 1), fieldName.substring(0, 1).toUpperCase());
        String getMethodName = "get" + fieldName;
        try {
            Method method = cls.getMethod(getMethodName);
            value = method.invoke(cls);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return value;
    }
}

最後看看幾個實用操作的寫法:修改既有檔案、複製並保留格式、以及讀回內容。

public class SaveToExcel {

    /** 直接在既有檔案上修改,並可加上粗體、底線 */
    public static void modifyDirectly2(File inputFile) throws Exception {
        Workbook w1 = Workbook.getWorkbook(inputFile);
        WritableWorkbook w2 = Workbook.createWorkbook(inputFile, w1);
        WritableSheet sheet = w2.getSheet(0);
        WritableCell cell = null;
        CellFormat cf = null;

        cell = sheet.getWritableCell(0, 0); // 加粗
        WritableFont bold = new WritableFont(WritableFont.ARIAL, WritableFont.DEFAULT_POINT_SIZE, WritableFont.BOLD);
        cf = new WritableCellFormat(bold);
        cell.setCellFormat(cf);

        cell = sheet.getWritableCell(0, 1); // 加底線
        WritableFont underline = new WritableFont(WritableFont.ARIAL, WritableFont.DEFAULT_POINT_SIZE, WritableFont.NO_BOLD, false, UnderlineStyle.SINGLE);
        cf = new WritableCellFormat(underline);
        cell.setCellFormat(cf);

        setCellValueDirectly(sheet, sheet.getCell(0, 2), new Double(4), CellType.NUMBER);
        w2.write();
        w2.close();
    }

    /** 複製檔案並保留原有格式、合併狀態與列寬列高 */
    public static void copyDateAndFormat(File inputFile, int inputFileSheetIndex, String outputFilePath) throws Exception {
        Workbook book = null;
        Cell cell = null;
        // 1. 避免亂碼的設定
        WorkbookSettings setting = new WorkbookSettings();
        java.util.Locale locale = new java.util.Locale("zh", "CN");
        setting.setLocale(locale);
        setting.setEncoding("ISO-8859-1");
        book = Workbook.getWorkbook(inputFile, setting);
        Sheet readonlySheet = book.getSheet(inputFileSheetIndex);
        OutputStream os = new FileOutputStream(outputFilePath);
        WritableWorkbook wwb = Workbook.createWorkbook(os);
        WritableSheet writableSheet = wwb.createSheet(readonlySheet.getName(), 0);

        // 2. 依型別逐格謄寫
        for (int rowIndex = 0; rowIndex < readonlySheet.getRows(); rowIndex++) {
            for (int colIndex = 0; colIndex < readonlySheet.getColumns(); colIndex++) {
                cell = readonlySheet.getCell(colIndex, rowIndex);
                if (cell.getType() == CellType.DATE || cell.getType() == CellType.DATE_FORMULA) {
                    writableSheet.addCell(new jxl.write.DateTime(colIndex, rowIndex, ((DateCell) cell).getDate(), new jxl.write.WritableCellFormat(cell.getCellFormat())));
                } else if (cell.getType() == CellType.NUMBER || cell.getType() == CellType.NUMBER_FORMULA) {
                    writableSheet.addCell(new jxl.write.Number(colIndex, rowIndex, ((jxl.NumberCell) cell).getValue(), new jxl.write.WritableCellFormat(cell.getCellFormat())));
                } else if (cell.getType() == CellType.LABEL || cell.getType() == CellType.STRING_FORMULA) {
                    writableSheet.addCell(new Label(colIndex, rowIndex, cell.getContents(), new jxl.write.WritableCellFormat(cell.getCellFormat())));
                }
                // EMPTY 與其它型別此處略過處理
            }
        }

        // 3. 還原合併儲存格
        Range[] range = readonlySheet.getMergedCells();
        for (int i = 0; i < range.length; i++) {
            writableSheet.mergeCells(range[i].getTopLeft().getColumn(), range[i].getTopLeft().getRow(),
                                     range[i].getBottomRight().getColumn(), range[i].getBottomRight().getRow());
        }

        // 4. 還原列寬與列高
        for (int colIndex = 0; colIndex < readonlySheet.getColumns(); colIndex++) {
            writableSheet.setColumnView(colIndex, readonlySheet.getColumnView(colIndex));
        }
        for (int rowIndex = 0; rowIndex < readonlySheet.getRows(); rowIndex++) {
            writableSheet.setRowView(rowIndex, readonlySheet.getRowView(rowIndex));
        }
        wwb.write();
        wwb.close();
        os.close();
    }

    /** 按型別直接覆寫儲存格的值 */
    public static void setCellValueDirectly(WritableSheet sheet, Cell cell, Object newValue, CellType type) throws Exception {
        if (type == CellType.DATE || type == CellType.DATE_FORMULA) {
            sheet.addCell(new jxl.write.DateTime(cell.getColumn(), cell.getRow(), (Date) newValue, new jxl.write.WritableCellFormat(cell.getCellFormat())));
        } else if (type == CellType.NUMBER || type == CellType.NUMBER_FORMULA) {
            sheet.addCell(new jxl.write.Number(cell.getColumn(), cell.getRow(), ((Double) newValue).doubleValue(), new jxl.write.WritableCellFormat(cell.getCellFormat())));
        } else if (type == CellType.LABEL || type == CellType.STRING_FORMULA) {
            sheet.addCell(new Label(cell.getColumn(), cell.getRow(), (String) newValue, new jxl.write.WritableCellFormat(cell.getCellFormat())));
        } else {
            throw new Exception("不支援的其它儲存格類型:" + type);
        }
    }
}

讀取時記得設定編碼,並且一定要關閉 book,否則在長期運行的環境中容易累積記憶體:

public static ArrayList<String> sampleReadExcel(File inputFile, int inputFileSheetIndex) throws Exception {
    ArrayList<String> list = new ArrayList<String>();
    WorkbookSettings setting = new WorkbookSettings();
    java.util.Locale locale = new java.util.Locale("zh", "CN");
    setting.setLocale(locale);
    setting.setEncoding("ISO-8859-1");
    Workbook book = Workbook.getWorkbook(inputFile, setting);
    Sheet sheet = book.getSheet(inputFileSheetIndex);
    for (int rowIndex = 0; rowIndex < sheet.getRows(); rowIndex++) {
        for (int colIndex = 0; colIndex < sheet.getColumns(); colIndex++) {
            Cell cell = sheet.getCell(colIndex, rowIndex);
            list.add(cell.getContents());
        }
    }
    book.close(); // 務必關閉,釋放資源
    return list;
}

以下是實際執行後的畫面:

小結

整體流程其實不長:介面收集輸入 → 寫入 SQLite → 從 Cursor 取出資料 → 逐列塞進 Sheet → write 並 close。真正需要留意的是兩件事:一是儲存格座標從 0 起算,容易與直覺的列號混淆;二是檔案輸出路徑在 Android 上牽涉到儲存空間權限,别忘了在清單中聲明。把這兩點處理好,匯出 Excel 就是一件相當平順的事。

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