WEB开发网
开发学院手机开发Android 开发 Android下Excel的操作 阅读

Android下Excel的操作

 2012-05-16 21:51:37 来源:WEB开发网   
核心提示: 在Android下操作Excel和在j2se下操作是一样的,下载一个jxl.jar包,Android下Excel的操作,导入到android工程的构建路径中,加入权限<uses-permission android:name="android.permission.WRITE_EXTERNAL_STO

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

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

以下是一个小例子。

//详细参考     http://www.ibm.com/developerworks/cn/java/l-javaExcel/
public class OperateExcelActivity extends Activity
{
     /** Called when the activity is first created. */
     @Override
     public void onCreate(Bundle savedInstanceState)
     {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.main);
         TextView textView = (TextView)findViewById(R.id.tv);
         String path = "mnt/sdcard/test.xls";
         writeExcel(path);
         textView.setText(readExcel(path,5,5)+readExcel(path,10,10));
     }
 
     public void writeExcel(String fileName)
     {
         WritableWorkbook wwb = null;
         try
         {
             //创建一个可写入的工作薄(Workbook)对象
             wwb = Workbook.createWorkbook(new File(fileName));
         } catch (IOException e)
         {
             e.printStackTrace();
         }
         if (wwb != null)
         {
             // 第一个参数是工作表的名称,第二个是工作表在工作薄中的位置
             WritableSheet ws = wwb.createSheet("sheet1", 0);
             // 在指定单元格插入数据
             Label lbl1 = new Label(5, 5, "Excel");
             Label bll2 = new Label(10, 10, "的操作");
             try
             {
                 ws.addCell(lbl1);
                 ws.addCell(bll2);
             } catch (RowsExceededException e1)
             {
                 e1.printStackTrace();
             } catch (WriteException e1)
             {
                 e1.printStackTrace();
             }
             try
             {
                 // 从内存中写入文件中
                 wwb.write();
                 wwb.close();
             } catch (IOException e)
             {
                 e.printStackTrace();
             } catch (WriteException e)
             {
                 e.printStackTrace();
             }
         }
     }
 
     public String readExcel(String path, int x, int y)
     {
         String content = "";
         try
         {
             Workbook book = Workbook.getWorkbook(new File(path));
             Sheet sheet = book.getSheet(0);
             //得到x行y列所在单元格的内容
             String cellStr = sheet.getRow(x)[y].getContents();
             content = cellStr;
 
         } catch (BiffException e)
         {
             content = "";
             e.printStackTrace();
         } catch (IOException e)
         {
             content = "";
             e.printStackTrace();
         } 
         return content;
         
 
     }
 
 }

Tags:Android Excel 操作

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接