操作Excel之导出数据成Excel

package com.java;

import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class ExportExcel {

/**
* 使用时请修改此方法
* @return
*/
public static List<Student> getStudent(){

List<Student> list = new ArrayList<Student>();

Student user1 = new Student("00001", "张三", "16","男");
Student user2 = new Student("00002", "李四", "17","女");
Student user3 = new Student("00003", "王五", "26","男");
list.add(user1);
list.add(user2);
list.add(user3);

return list;
}

/**
* Excel导出方法,导出为2003格式
* @return
*/
public String exportExcel(List list){
// 第一步,创建一个webbook,对应一个Excel文件
HSSFWorkbook wb = new HSSFWorkbook();
// 第二步,在webbook中添加一个sheet,对应Excel文件中的sheet
HSSFSheet sheet = wb.createSheet();
// 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
HSSFRow row = sheet.createRow((int) 0);
// 第四步,创建单元格,并设置值表头 设置表头居中
HSSFCellStyle style = wb.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
style.setVerticalAlignment(HSSFCellStyle.ALIGN_CENTER);

HSSFCell cell = row.createCell(0);
cell.setCellValue("学号");
cell.setCellStyle(style);

cell = row.createCell(1);
cell.setCellValue("姓名");
cell.setCellStyle(style);

cell = row.createCell(2);
cell.setCellValue("年龄");
cell.setCellStyle(style);

cell = row.createCell(3);
cell.setCellValue("性别");
cell.setCellStyle(style);

for (int i = 0; i < list.size(); i++) {
row = sheet.createRow((int) i + 1);
Student stu = (Student) list.get(i);
// 第四步,创建单元格,并设置值
HSSFCell ce = row.createCell(0);
ce.setCellType(HSSFCell.CELL_TYPE_STRING);//设置单元格格式为文本格式
ce.setCellValue(String.valueOf(stu.getId()));
row.createCell(1).setCellValue(stu.getName());
row.createCell(2).setCellValue(stu.getAge());
row.createCell(3).setCellValue(stu.getSex());
cell = row.createCell(4);
}
// 第六步,将文件存到指定位置
try {
FileOutputStream fout = new FileOutputStream("c:\\Users\\Administrator\\Desktop\\Test1.xlsx");
wb.write(fout);
fout.close();
}
catch (Exception e) {
e.printStackTrace();
return "FAIL";
}
return "SUCCESS";
}

public static void main(String[] args) {
List<Student> list = new ArrayList<Student>();
Student user1 = new Student("00001", "张三", "16","男");
Student user2 = new Student("00002", "李四", "17","女");
Student user3 = new Student("00003", "王五", "26","男");
list.add(user1);
list.add(user2);
list.add(user3);
ExportExcel excel = new ExportExcel();
excel.exportExcel(list);
}
}

猜你喜欢

转载自www.cnblogs.com/chenligeng/p/11051510.html