一、pom.xml添加依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.0</version>
</dependency>
二、导出
package com.example.testpoi.controller;
import com.example.testpoi.entity.emp;
import com.example.testpoi.service.DcService;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
@RestController
@RequestMapping("/dc")
public class DcController {
@Autowired
private DcService dcService;
@RequestMapping(value = "/dc")
public void dc(HttpServletResponse response){
List<emp> emps = dcService.getData();
response.setContentType("application/binary;charset=urt-8");
String title = "员工表";
String filename = "Scott员工表";
try {
response.setHeader("Content-Disposition","attachment;fileName=" + URLEncoder.encode(filename + ".xls", "UTF-8"));
HSSFWorkbook workbook = new HSSFWorkbook(); //创建工作簿
HSSFSheet sheet = workbook.createSheet(title); //工作表
HSSFRow row = sheet.createRow(0); //第一行
String headers[] = {"员工编号","员工姓名","员工职位","上司编号","员工生日"}; //表头
int width[] = {4000,4000,4000,4000,4000};
//设置表头
HSSFCell cell = null;
for (int i=0; i<headers.length; i++){
cell = row.createCell(i);
cell.setCellValue(headers[i]);
sheet.setColumnWidth(i,width[i]);
}
//设置表体
int rowCount = 1; //第二行开始
for (emp e: emps) {
row = sheet.createRow(rowCount);
row.createCell(0).setCellValue(e.getEmpno());
row.createCell(0).setCellValue(e.getEname());
row.createCell(0).setCellValue(e.getJob());
row.createCell(0).setCellValue(e.getMgr());
row.createCell(0).setCellValue(e.getHiredate());
rowCount ++;
}
OutputStream out = response.getOutputStream();
workbook.write(out);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
来源:oschina
链接:https://my.oschina.net/u/4335884/blog/3367751