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");
}
}
excel導出基礎例子
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.