在Android中使用第三方庫來實現對excel的文件的導入導出
準備操作:從網絡上下載第三方庫jxl.jar並且導入到Android studio中
一、將內存中的數據導出到Excel文件中。
/**
* Created by Administrator on 2017/3/7.\
* 將數據導出成文excel文件
* 使用sqlite創建一個本地的結果表 將這個結果表映射成爲一個實體類 將整個實體類轉化成excel表格
*/
//將內存中創建的實體類,保存爲excel文件
public class ExpportDataBeExcel {
public void exportData(List<BeanExportData> datas){
//需要導出的excel文件的文件名
String fileName ="考情統計.xls";
//操作excel的對象
WritableWorkbook wwb = null;
try {
//根據當前的文件路徑創建統計的文件並且實例化出一個操作excel的對象
wwb = Workbook.createWorkbook(new File(Environment.getExternalStorageDirectory()+"/"+fileName));
} catch (IOException e) {
e.printStackTrace();
}
if (wwb != null ){
//創建底部的選項卡 傳參是選項卡的名稱 和 選型卡的索引
WritableSheet writableSheet = wwb.createSheet("2017年3月7日考勤",0);
//創建excel的表頭的信息
String [] topic ={"序號","姓名","年齡","日期"};
for (int i = 0 ; i<topic.length ; i++ ){
//橫向的在單元格中填寫數據
Label labelC = new Label(i,0,topic[i]);
try {
writableSheet.addCell(labelC);
} catch (WriteException e) {
e.printStackTrace();
}
}
//從實體中遍歷數據並將數據寫入excel文件中
BeanExportData account;
ArrayList<String> li;
for ( int j = 0 ; j < datas.size() ; j++ ){
//將數據源列表中的數據整合成 一個個的字符串列表
account = datas.get(j);
li = new ArrayList<>();
li.add(account.getNumber());
li.add(account.getName());
li.add(account.getAge());
li.add(account.getData());
int k = 0;
for (String l:li){
//將單個的字符串列表橫向的填入到excel表中
Label labelC = new Label(k,j+1,l);
k++;
try {
writableSheet.addCell(labelC);
} catch (WriteException e) {
e.printStackTrace();
}
}
li = null;
}
}
//將文件從內存寫入到文件當中
try {
wwb.write();
wwb.close();
} catch (IOException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
}
}
}
二、將Excel文件中的內容導入到內存
public class ImportDataFromExcel {
//將excel文件導入到內存中
private List<BeanExportData> datas;
public String ImportExcelData(){
datas = new ArrayList<>();
Workbook workbook = null;
String fileName ="考情統計.xls";
try {
workbook = Workbook.getWorkbook(new File(Environment.getExternalStorageDirectory()+"/"+fileName));
Sheet sheet = workbook.getSheet(0);
int rows = sheet.getRows();
int columns = sheet.getColumns();
//遍歷excel文件的每行每列
for (int i=0; i < rows ;i++){
//遍歷行
List<String> li = new ArrayList<>();
for (int j = 0 ; j < columns ; j++ ){
Cell cell = sheet.getCell(j,i);
String result = cell.getContents();
if (i!=0){
li.add(result);
}
}
if (li.size()>0){
datas.add(new BeanExportData(li.get(0),li.get(1),li.get(2),li.get(3)));
}
li = null;
}
Gson gson = new Gson();
return gson.toJson(datas);
} catch (IOException e) {
e.printStackTrace();
} catch (BiffException e) {
e.printStackTrace();
}
return "error";
}
}
這裏寫鏈接內容
許不了你的一世溫柔,沒錯。我就是一個有情懷的程序員。