使用Java将数据导出到Excel中,需要引用第三方的jar包,这里我使用的maven,在maven中导入如下包:
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.10.1</version> </dependency>
如果不使用maven,则可以直接到网上搜索poi下载,下面具体实现导出Excel
首先创建一个实体类:
package com.tenghu.export_excel.model; /** * Created by Arvin on 2014/11/12. */ public class Employees { private int id; private String code; private String name; private String position; private String department; public Employees() { } public Employees(int id, String code, String name, String position, String department) { this.id = id; this.code = code; this.name = name; this.position = position; this.department = department; } //省略get和set方法 }使用一个测试类来导出Excel
package com.tenghu.export_excel.test; import com.tenghu.export_excel.model.Employees; import org.apache.poi.hssf.usermodel.*; import org.apache.poi.ss.usermodel.CellStyle; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * Created by Arvin on 2014/11/12. */ public class ExportExcelTest { public static List<Employees> getEmployeesList(){ List<Employees> employeesList=new ArrayList<Employees>(); employeesList.add(new Employees(1,"PT_001","张三","销售主管","销售部")); employeesList.add(new Employees(2,"PT_002","李四","销售经理","销售部")); employeesList.add(new Employees(3,"PT_003","王五","市场策划","市场部")); employeesList.add(new Employees(4,"PT_004","赵二","客服","客服部")); return employeesList; } public static void main(String[] args){ //实例化HSSFWorkbook对象,相当于新建一个Excel文件 HSSFWorkbook workbook=new HSSFWorkbook(); //根据HSSFWorkbook获取Sheet HSSFSheet sheet=workbook.createSheet(); //添加一行作为表格头 HSSFRow header=sheet.createRow(0); //创建表格样式 HSSFCellStyle cellStyle=workbook.createCellStyle(); cellStyle.setAlignment(CellStyle.ALIGN_CENTER);//内容居中显示 //创建头部表格 HSSFCell cell=header.createCell(0); cell.setCellStyle(cellStyle); cell.setCellValue("序号"); cell=header.createCell(1); cell.setCellStyle(cellStyle); cell.setCellValue("员工编号"); cell=header.createCell(2); cell.setCellStyle(cellStyle); cell.setCellValue("员工姓名"); cell=header.createCell(3); cell.setCellStyle(cellStyle); cell.setCellValue("员工职位"); cell=header.createCell(4); cell.setCellStyle(cellStyle); cell.setCellValue("员工部门"); //获取员工集合 List<Employees> employeesList=getEmployeesList(); for(int i=0;i<employeesList.size();i++){ HSSFRow content=sheet.createRow(i+1); //获取员工 Employees employees=employeesList.get(i); //创建单元格并设置值 content.createCell(0).setCellValue(employees.getId()); content.createCell(1).setCellValue(employees.getCode()); content.createCell(2).setCellValue(employees.getName()); content.createCell(3).setCellValue(employees.getPosition()); content.createCell(4).setCellValue(employees.getDepartment()); } try { //写入文件 FileOutputStream fileOutputStream=new FileOutputStream("D:/员工信息.xls"); workbook.write(fileOutputStream); fileOutputStream.close(); System.out.println("导出成功!"); } catch (IOException e) { e.printStackTrace(); System.out.println("导出失败!"); } } }