在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();
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
二、将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";
}
}
将数据转成.xls excel表格导出
https://github.com/DmrfCoder/AndroidExcelDemo