import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class CreateExcelPOI {
public static void main(String[] args) {
Student st1 = new Student("jack", 25, 45.2);
Student st2 = new Student("张三", 29, 45.2);
Student st3 = new Student("si.li", 55, 45.2);
Student st4 = new Student("dan", 32, 45);
List<Student> list = new ArrayList<Student>();
list.add(st1);
list.add(st2);
list.add(st3);
list.add(st4);
// 第一步,创建一个webbook,对应一个Excel文件
// 根据要求创建对应版本的文件
XSSFWorkbook wb = new XSSFWorkbook();// 创建.xlsx,不能正确创建.xls文件
// HSSFWorkbook wb = new HSSFWorkbook(); //创建.xls,不能创建正确的.xlsx
// 第二步,在webbook中添加一个sheet,对应Excel文件中的sheet
XSSFSheet sheet = wb.createSheet("测试生成Excel表"); // sheet的名称
XSSFSheet sheet1 = wb.createSheet("测试生成Excel表-2"); // 相当于sheet2
// 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
XSSFRow row = sheet.createRow(0);
// 第四步,创建单元格,并设置值表头 设置表头居中
XSSFCellStyle style = wb.createCellStyle();
style.setAlignment(XSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
XSSFCell 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);
for (int i = 0; i < list.size(); i++) {
row = sheet.createRow(i + 1); // 每次循环增加一行数据
Student stu = (Student) list.get(i);
// row.createCell(0).setCellValue(stu.getName());
XSSFCell cell0 = row.createCell(0);
cell0.setCellValue(stu.getName());
cell0.setCellStyle(style);// 第一列居中
row.createCell(1).setCellValue(stu.getAge());
row.createCell(2).setCellValue(stu.getTizhong());
}
try {
String date = new SimpleDateFormat("YYYY-MM-dd_HH_mm_ss").format(new Date());
FileOutputStream fout = new FileOutputStream("K:/students" + date + ".xlsx");
wb.write(fout);
fout.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}