1、項目結構
2、準備jar包只需要jxl.jar就可以
3、書寫Jxl2Excel.java
package com.hhj.excel;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import com.hhj.domain.User;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;
public class Jxl2Excel {
public static void createTitle(WritableSheet sheet,List<String> list) throws RowsExceededException, WriteException{
if(list!=null && list.size()>0){
WritableFont wf = new WritableFont(WritableFont.ARIAL, 18,WritableFont.BOLD, false,jxl.format.UnderlineStyle.NO_UNDERLINE,jxl.format.Colour.BLACK);
WritableCellFormat wcfF = new WritableCellFormat(wf);
for(int i=0;i<list.size();i++) {
Label label = new Label(i, 0, list.get(i), wcfF);
sheet.addCell(label);
}
}
}
public static void main(String[] args) throws Exception {
File file = new File("F:\\test.xls");
if (!file.exists()) {
file.createNewFile();
}
//創建一個excel
WritableWorkbook book = Workbook.createWorkbook(file);
//生成名爲"信息"的sheet,參數0表示這是第一頁
WritableSheet sheet1 = book.createSheet("信息", 0);
WritableSheet sheet2 = book.createSheet("信息2", 1);
//標題list
List<String> lt = new ArrayList<String>();
lt.add("賬號");
lt.add("姓名");
lt.add("電話號碼");
//創建標題
createTitle(sheet1, lt);
// 內容list
List<User> list = new ArrayList<User>();
User user = new User();
user.setAccount("001");
user.setName("123");
user.setTel("11111");
list.add(user);
User user1 = new User();
user1.setAccount("002");
user1.setName("456");
user1.setTel("22222");
list.add(user1);
for(int i=0;i<list.size();i++) {
int x = 0;
Label label = new Label(x++, i+1, list.get(i).getAccount());
Label label2 = new Label(x++, i+1, list.get(i).getName());
Label label3 = new Label(x++, i+1, list.get(i).getTel());
sheet1.addCell(label);
sheet1.addCell(label2);
sheet1.addCell(label3);
}
book.write();
book.close();
System.out.println("生成excel文件成功");
}
}
4、domain類User.java
package com.hhj.domain;
public class User {
private String account;
private String name;
private String tel;
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
}
總結:
使用jxl導出excel相對來說比較簡單,整體只需要三步
1.WritableWorkbook book = Workbook.createWorkbook(file);
2.WritableSheet sheet1 = book.createSheet("信息", 0); //0表示從第一列開始
3.Label label = new Label(x++, i+1, list.get(i).getAccount());
sheet1.addCell(label);
本人郵箱<a href="[email protected]"></a>