excel导出基础例子

来源:互联网 发布:尾气分析仪数据分析 编辑:程序博客网 时间:2024/05/02 00:27
public class test {    public static String export(List ublist,String path)            throws Exception {        try {            File tempFile = new File(path);            File accessory = new File(tempFile.getParent());            if (!accessory.exists()) {                accessory.mkdirs();            }        } catch (Exception e) {            throw new Exception("导出路径不存在或上次导出的文件正处于打开状态,请先关闭在导出");        }        if (ublist != null) {            WritableWorkbook book = null;            try {                book = Workbook.createWorkbook(new File(path));                WritableSheet sheet = book.createSheet("excel测试", 0);                //这里需要注意的是,在Label中,第一个参数表示列,第二个表示行                Label templabe1 = new Label(0, 0, "年龄"); // 标题                sheet.addCell(templabe1);                Label templabe2 = new Label(1, 0, "姓名");                 sheet.addCell(templabe2);                                for (int i = 0; i < ublist.size(); i++) {                    UserBean sjdhBean = (UserBean) ublist.get(i);                    Label labe =  new Label(0, i+1, String.valueOf(sjdhBean.getAge()));                    Label labe2 = new Label(1, i+1, sjdhBean.getName());                                         sheet.addCell(labe);                    sheet.addCell(labe2);                }                book.write();            } catch (Exception e){                e.printStackTrace();            } finally {                if(book!=null){                    book.close();                }            }        } else {            throw new Exception("要导出的文件没有记录");        }        return "";    }    public static void main(String[] args) throws Exception {        List<UserBean> ublist = new ArrayList<UserBean>();        UserBean ub1 = new UserBean();        ub1.setName("zhangsan");        ub1.setAge(1);        UserBean ub2 = new UserBean();        ub2.setName("lisi");        ub2.setAge(2);        ublist.add(ub1);        ublist.add(ub2);        export(ublist, "F:\\aa.xls");    }}

0 0