HSSFWorkbook使用java代码导出excel

时间:2024-05-18 21:45:39

 

public class Excel {

 

 

public static void main(String[] args) {
try {
FileOutputStream out = new FileOutputStream("e:\\aaa.xls");//要输出的文件名字
HSSFWorkbook workBook = new HSSFWorkbook();
HSSFSheet mySheet = workBook.createSheet();//创建一个工作薄
workBook.setSheetName(0, "我的工作簿1",HSSFWorkbook.ENCODING_UTF_16);//设置名字(以及编码)
HSSFRow myRow = mySheet.createRow(0);//创建 并设置第一行
HSSFCellStyle style = workBook.createCellStyle();

style.setAlignment(HSSFCellStyle.ALIGN_CENTER);//对齐方式
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);//上下左右边框
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);

HSSFFont font = workBook.createFont();//设置字体样式
font.setFontName("宋体");
font.setFontHeightInPoints((short) 10);
font.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
style.setFont(font);

HSSFCell cell = myRow.createCell((short) 0);
cell.setCellStyle(style);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue("姓名");

cell = myRow.createCell((short) 1);
cell.setCellStyle(style);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue("性别");

cell = myRow.createCell((short) 2);
cell.setCellStyle(style);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue("呵呵");

List<Users> list = new Excel().getUsers();//得到查询数据(模拟数据库查询)
for(int i = 1; i <= list.size(); i++){
myRow = mySheet.createRow(i);
Users user = list.get(i-1);

cell = myRow.createCell((short) 0);//创建单元格  先设置样式、编码,然后再置值。
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue(user.getName());


cell = myRow.createCell((short) 1);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue(user.getSex());

cell = myRow.createCell((short) 2);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue(user.getHobby());

}
workBook.write(out);//写出文件
out.close();

} catch (Exception e) {
e.printStackTrace();
}

}

public List<Users> getUsers(){
List<Users> users = new ArrayList<Users>();
Users u = new Users();
u.setHobby("吃饭");
u.setName("张三");
u.setSex("男");
Users u1 = new Users();
u1.setHobby("睡觉");
u1.setName("李四");
u1.setSex("女");
users.add(u);
users.add(u1);

return users;
}

}

 

注:给cell(单元格)置值一定要在设置单元格各属性之后。

HSSFWorkbook使用java代码导出excel