Java生成Excel并导入数据

1.引入相关jar包(maven的)

<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.14</version>
</dependency>

2,编写代码
public static void main(String[] args) {
//1.创建一个workbook对应一个excel文件
HSSFWorkbook workbook=new HSSFWorkbook();
//设置样式
HSSFCellStyle cellStyle=workbook.createCellStyle();
//设置居中
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
//2.在workbook中创建一个sheet对应excel中的sheet
HSSFSheet sheet=workbook.createSheet("数据统计");
//设置所有数据都当成文本显示
CellStyle textStyle=workbook.createCellStyle();
DataFormat format=workbook.createDataFormat();
textStyle.setDataFormat(format.getFormat("0"));
    //得到要导出的数据
ArrayList<StuEntity> sel=new ArrayList<>();
StuEntity se = new StuEntity();
se.setId(1);
se.setName("张三");
se.setSex("女");
se.setNum(34);
sel.add(se);
StuEntity se1 = new StuEntity();
se1.setId(2);
se1.setName("里斯");
se1.setSex("男");
se1.setNum(44);
sel.add(se1);

for(int q=0;q<sel.size();q++){
sheet.setDefaultColumnStyle(q,textStyle);
}
sheet.setColumnWidth(0,256*25);
//设置表格第一行显示标题
HSSFRow row1=sheet.createRow(0);
HSSFCell cell=row1.createCell(1);
cell.setCellValue("编号");
cell=row1.createCell(2);
cell.setCellValue("姓名");
cell=row1.createCell(3);
cell.setCellValue("性别");
cell=row1.createCell(4);
cell.setCellValue("年龄");


int num=1;
for(int a=0;a<sel.size();a++){
StuEntity stu=sel.get(a);
HSSFRow row=null;
if(sheet.getRow(num)==null){
row=sheet.createRow(num);
}else{
row=sheet.getRow(num);
}
num++;
row.createCell(1).setCellValue(stu.getId());
row.createCell(2).setCellValue(stu.getName());
row.createCell(3).setCellValue(stu.getSex());
row.createCell(4).setCellValue(stu.getNum());
}

//将文件保存到指定的位置
try {

FileOutputStream fos = new FileOutputStream("E:\统计.xls");
workbook.write(fos);
System.out.println("写入成功");
fos.close();
} catch (IOException e) {
e.printStackTrace();
}


3.效果图如下:

导出的数据


原文地址:https://www.cnblogs.com/taosheng-yijiu/p/13274935.html