0
点赞
收藏
分享

微信扫一扫

Android下Excel的操作


在Android下操作Excel和在j2se下操作是一样的,下载一个jxl.jar包,导入到android工程的构建路径中。加入权限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
 <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>

以下是一个小例子。





1 //详细参考     http://www.ibm.com/developerworks/cn/java/l-javaExcel/
 2 public class OperateExcelActivity extends Activity
 3 {
 4     
 5     @Override
 6     public void onCreate(Bundle savedInstanceState)
 7     {
 8         super.onCreate(savedInstanceState);
 9         setContentView(R.layout.main);
10         TextView textView = (TextView)findViewById(R.id.tv);
11         String path = "mnt/sdcard/test.xls";
12         writeExcel(path);
13         textView.setText(readExcel(path,5,5)+readExcel(path,10,10));
14     }
15 
16     public void writeExcel(String fileName)
17     {
18         WritableWorkbook wwb = null;
19         try
20         {
21             //创建一个可写入的工作薄(Workbook)对象
22             wwb = Workbook.createWorkbook(new File(fileName));
23         } catch (IOException e)
24         {
25             e.printStackTrace();
26         }
27         if (wwb != null)
28         {
29             // 第一个参数是工作表的名称,第二个是工作表在工作薄中的位置
30             WritableSheet ws = wwb.createSheet("sheet1", 0);
31             // 在指定单元格插入数据
32             Label lbl1 = new Label(5, 5, "Excel");
33             Label bll2 = new Label(10, 10, "的操作");
34             try
35             {
36                 ws.addCell(lbl1);
37                 ws.addCell(bll2);
38             } catch (RowsExceededException e1)
39             {
40                 e1.printStackTrace();
41             } catch (WriteException e1)
42             {
43                 e1.printStackTrace();
44             }
45             try
46             {
47                 // 从内存中写入文件中
48                 wwb.write();
49                 wwb.close();
50             } catch (IOException e)
51             {
52                 e.printStackTrace();
53             } catch (WriteException e)
54             {
55                 e.printStackTrace();
56             }
57         }
58     }
59 
60     public String readExcel(String path, int x, int y)
61     {
62         String content = "";
63         try
64         {
65             Workbook book = Workbook.getWorkbook(new File(path));
66             Sheet sheet = book.getSheet(0);
67             //得到x行y列所在单元格的内容
68             String cellStr = sheet.getRow(x)[y].getContents();
69             content = cellStr;
70 
71         } catch (BiffException e)
72         {
73             content = "";
74             e.printStackTrace();
75         } catch (IOException e)
76         {
77             content = "";
78             e.printStackTrace();
79         } 
80         return content;
81         
82 
83     }
84 
85 }

举报

相关推荐

0 条评论