java对Execl的导入导出

来源:互联网 发布:博彦科技面试题java 编辑:程序博客网 时间:2024/05/29 12:16

一、用到的包

项目用到的包是jxl包下载地址是:jxl.jar密码是:链接:11bg


二、实现步骤     

第一步:新建工程

第二步:引入jxl.jav的和mysql-connector-java.jar

第三步:新建ExeclOperation和DataBaseUtil工具类

三、代码实现

package com.execlExport.util;import java.io.File;import java.io.IOException;import java.util.ArrayList;import java.util.List;import jxl.Cell;import jxl.Sheet;import jxl.Workbook;import jxl.read.biff.BiffException;import jxl.write.Label;import jxl.write.WritableSheet;import jxl.write.WritableWorkbook;import jxl.write.WriteException;import jxl.write.biff.RowsExceededException;import com.execlExport.model.StudentBean;/** * ExeclOperation  * 创建人: TanZi * 时间: 2015-1-20 下午4:30:44 * 作用: 对Execl文件的操作 */public class ExeclOperation {/** *作用:向execl中写入数据 * @param list */public  void exportExecl(List<StudentBean> list){//execl的表头String[] title={"id","username","password"};//创建一个副本。WritableWorkbook wwb=null;//创建一个excel文件。File f=new File("d://astudent.xls");try {//创建一个excel对象wwb=Workbook.createWorkbook(f);//创建一个工作区间WritableSheet sheet=wwb.createSheet("TanZi", 0);//把表头写到Execl中去Label label1=null;for(int i=0;i<title.length;i++){label1=new Label(i, 0, title[1]);sheet.addCell(label1);}//把数据写到副本中去for(int i=0;i<list.size();i++){StudentBean stu=list.get(i);label1=new Label(0,i+1,stu.getId());sheet.addCell(label1);label1=new Label(1,i+1,stu.getUsername());sheet.addCell(label1);label1=new Label(2,i+1,stu.getPassword());sheet.addCell(label1);}wwb.write();//副本写入到execl中去wwb.close();//关闭流} catch (IOException e) {e.printStackTrace();} catch (RowsExceededException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (WriteException e) {// TODO Auto-generated catch blocke.printStackTrace();}}/** *作用:从execl中读取数据 * @return  list 信息集 */public static List<StudentBean> importExecl(){List<StudentBean> list=new ArrayList<StudentBean>();File f=new File("d://astudent.xls");Workbook workbook=null;try {//获得文件workbook = Workbook.getWorkbook(f);//获得文件的sheetSheet sheet=workbook.getSheet(0);Cell cell=null;//从sheet读数据到listfor(int i=1;i<sheet.getRows();i++){StudentBean stu=new StudentBean();cell=sheet.getCell(0, i);//读取数据到cellstu.setId(cell.getContents());//获得cell中的内容cell=sheet.getCell(1, i);stu.setUsername(cell.getContents());cell=sheet.getCell(2, i);stu.setPassword(cell.getContents());    list.add(stu);}} catch (BiffException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return list;}}

四、网上扩展

别的博客









0 0