這篇文章主要介紹Android開發(fā)如何實(shí)現(xiàn)導(dǎo)出數(shù)據(jù)庫到Excel表格功能,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!
創(chuàng)新互聯(lián)是一家集網(wǎng)站建設(shè),資源企業(yè)網(wǎng)站建設(shè),資源品牌網(wǎng)站建設(shè),網(wǎng)站定制,資源網(wǎng)站建設(shè)報(bào)價(jià),網(wǎng)絡(luò)營銷,網(wǎng)絡(luò)優(yōu)化,資源網(wǎng)站推廣為一體的創(chuàng)新建站企業(yè),幫助傳統(tǒng)企業(yè)提升企業(yè)形象加強(qiáng)企業(yè)競爭力??沙浞譂M足這一群體相比中小企業(yè)更為豐富、高端、多元的互聯(lián)網(wǎng)需求。同時(shí)我們時(shí)刻保持專業(yè)、時(shí)尚、前沿,時(shí)刻以成就客戶成長自我,堅(jiān)持不斷學(xué)習(xí)、思考、沉淀、凈化自己,讓我們?yōu)楦嗟钠髽I(yè)打造出實(shí)用型網(wǎng)站。
具體如下:
之前一直在電腦上用Excel表格記錄家庭帳單,不久前重裝系統(tǒng)不小心干掉了,傷心了好久,那可是我記了五年的帳單呀!這段時(shí)間用的是隨手記,好用但是不太符合我的習(xí)慣,所以我自己寫了一個(gè)小小的帳單記錄APP,App小到只有一個(gè)Activity。當(dāng)然更多的需求我正在研發(fā)中,呵呵!現(xiàn)在已經(jīng)完成了把每天記錄的數(shù)據(jù)保存到Sqilte數(shù)據(jù)庫中,然后可以導(dǎo)出到excel表格。代碼也是借助網(wǎng)上的一些資料寫成的,代碼也比較容易,只需要用到一個(gè)jxl.jar包,感謝網(wǎng)友的幫助。
貼上主要代碼,再附上文件包:
MainActivity.java:
package com.ldm.familybill; import java.io.File; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import android.annotation.SuppressLint; import android.app.Activity; import android.content.ContentValues; import android.database.Cursor; import android.os.Bundle; import android.os.Environment; import android.text.TextUtils; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.ldm.db.DBHelper; import com.ldm.excel.ExcelUtils; @SuppressLint("SimpleDateFormat") 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 File file; private String[] title = { "日期", "食物支出", "日用品項(xiàng)", "交通話費(fèi)", "旅游出行", "穿著支出", "醫(yī)療保健", "人情客往", "寶寶專項(xiàng)", "房租水電", "其它支出", "備注說明" }; private String[] saveData; private DBHelper mDbHelper; private ArrayList<ArrayList<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<ArrayList<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); } @Override public void onClick(View v) { if (v.getId() == R.id.family_bill_save) { saveData = new String[] { new SimpleDateFormat("yyyy-MM-dd").format(new Date()), mFoodEdt.getText().toString().trim(), mArticlesEdt.getText().toString().trim(), mTrafficEdt.getText().toString().trim(), mTravelEdt.getText().toString().trim(), mClothesEdt.getText().toString().trim(), mDoctorEdt.getText().toString().trim(), mRenQingEdt.getText().toString().trim(), mBabyEdt.getText().toString().trim(), mLiveEdt.getText().toString().trim(), mOtherEdt.getText().toString().trim(), mRemarkEdt.getText().toString().trim() }; if (canSave(saveData)) { ContentValues values = new ContentValues(); values.put("time", new SimpleDateFormat("yyyy-MM-dd").format(new Date())); values.put("food", mFoodEdt.getText().toString()); values.put("use", mArticlesEdt.getText().toString()); values.put("traffic", mTrafficEdt.getText().toString()); values.put("travel", mTravelEdt.getText().toString()); values.put("clothes", mClothesEdt.getText().toString()); values.put("doctor", mDoctorEdt.getText().toString()); values.put("laiwang", mRenQingEdt.getText().toString()); values.put("baby", mBabyEdt.getText().toString()); values.put("live", mLiveEdt.getText().toString()); values.put("other", mOtherEdt.getText().toString()); values.put("remark", mRemarkEdt.getText().toString()); long insert = mDbHelper.insert("family_bill", values); if (insert > 0) { initData(); } } else { Toast.makeText(this, "請?zhí)顚懭我庖豁?xiàng)內(nèi)容", Toast.LENGTH_SHORT).show(); } } } @SuppressLint("SimpleDateFormat") public void initData() { file = new File(getSDPath() + "/Family"); makeDir(file); ExcelUtils.initExcel(file.toString() + "/bill.xls", title); ExcelUtils.writeObjListToExcel(getBillData(), getSDPath() + "/Family/bill.xls", this); } private ArrayList<ArrayList<String>> getBillData() { Cursor mCrusor = mDbHelper.exeSql("select * from family_bill"); while (mCrusor.moveToNext()) { ArrayList<String> beanList=new ArrayList<String>(); beanList.add(mCrusor.getString(1)); beanList.add(mCrusor.getString(2)); beanList.add(mCrusor.getString(3)); beanList.add(mCrusor.getString(4)); beanList.add(mCrusor.getString(5)); beanList.add(mCrusor.getString(6)); beanList.add(mCrusor.getString(7)); beanList.add(mCrusor.getString(8)); beanList.add(mCrusor.getString(9)); beanList.add(mCrusor.getString(10)); beanList.add(mCrusor.getString(11)); beanList.add(mCrusor.getString(12)); bill2List.add(beanList); } mCrusor.close(); return bill2List; } public static void makeDir(File dir) { if (!dir.getParentFile().exists()) { makeDir(dir.getParentFile()); } dir.mkdir(); } public String getSDPath() { File sdDir = null; boolean sdCardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED); if (sdCardExist) { sdDir = Environment.getExternalStorageDirectory(); } String dir = sdDir.toString(); return dir; } private boolean canSave(String[] data) { boolean isOk = false; for (int i = 0; i < data.length; i++) { if (i > 0 && i < data.length) { if (!TextUtils.isEmpty(data[i])) { isOk = true; } } } return isOk; } }
CreateExcel.java:
package com.ldm.excel; import java.io.File; import jxl.Workbook; import jxl.write.Label; import jxl.write.WritableSheet; import jxl.write.WritableWorkbook; import android.os.Environment; public class CreateExcel { // 準(zhǔn)備設(shè)置excel工作表的標(biāo)題 private WritableSheet sheet; /**創(chuàng)建Excel工作薄*/ private WritableWorkbook wwb; private String[] title = { "日期", "食物支出", "日用品項(xiàng)", "交通話費(fèi)", "旅游出行", "穿著支出", "醫(yī)療保健", "人情客往", "寶寶專項(xiàng)", "房租水電", "其它支出", "備注說明" }; public CreateExcel() { excelCreate(); } 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); /**添加第一個(gè)工作表并設(shè)置第一個(gè)Sheet的名字*/ sheet = wwb.createSheet("家庭帳務(wù)表", 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+1行, 單元格的內(nèi)容是y * 在Label對象的子對象中指明單元格的位置和內(nèi)容 * */ label = new Label(i, 0, title[i]); /**將定義好的單元格添加到工作表中*/ sheet.addCell(label); } /* * 把數(shù)據(jù)填充到單元格中 * 需要使用jxl.write.Number * 路徑必須使用其完整路徑,否則會出現(xiàn)錯(cuò)誤 */ for (int i = 0; i < title.length; i++) { Label labeli = new Label(i, index, content[i]); sheet.addCell(labeli); } // 寫入數(shù)據(jù) wwb.write(); // 關(guān)閉文件 wwb.close(); } }
DBHelper.java:
package com.ldm.db; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.database.sqlite.SQLiteOpenHelper; public class DBHelper extends SQLiteOpenHelper { public static final String DB_NAME = "ldm_family"; // DB name 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); } /** * 用戶第一次使用軟件時(shí)調(diào)用的操作,用于獲取數(shù)據(jù)庫創(chuàng)建語句(SW),然后創(chuàng)建數(shù)據(jù)庫 */ @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) { } /* 打開數(shù)據(jù)庫,如果已經(jīng)打開就使用,否則創(chuàng)建 */ public DBHelper open() { if (null == mDbHelper) { mDbHelper = new DBHelper(mcontext); } db = mDbHelper.getWritableDatabase(); return this; } /* 關(guān)閉數(shù)據(jù)庫 */ public void close() { db.close(); mDbHelper.close(); } /**添加數(shù)據(jù) */ public long insert(String tableName, ContentValues values) { return db.insert(tableName, null, values); } /**查詢數(shù)據(jù)*/ 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); } }
ExcelUtils.java:
package com.ldm.excel; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import jxl.Workbook; import jxl.WorkbookSettings; import jxl.write.Label; import jxl.write.WritableCell; import jxl.write.WritableCellFormat; import jxl.write.WritableFont; import jxl.write.WritableSheet; import jxl.write.WritableWorkbook; import jxl.write.WriteException; import android.content.Context; import android.widget.Toast; 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("家庭帳務(wù)表", 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) { // TODO Auto-generated catch block 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(); } } } } } 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; } }
以上是“Android開發(fā)如何實(shí)現(xiàn)導(dǎo)出數(shù)據(jù)庫到Excel表格功能”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關(guān)知識,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!
文章名稱:Android開發(fā)如何實(shí)現(xiàn)導(dǎo)出數(shù)據(jù)庫到Excel表格功能
文章分享:http://jinyejixie.com/article28/posjjp.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站策劃、動(dòng)態(tài)網(wǎng)站、App開發(fā)、定制網(wǎng)站、靜態(tài)網(wǎng)站、營銷型網(wǎng)站建設(shè)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)