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="hehujun@126.com"></a>