依赖包
<!-- POI包 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.8</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.8</version>
</dependency>
Controller 层定义
@RestController
public class StdandardDirectoryController {
/**
* 下载标准化字典Excel导入模版
* @return Object 状态码
*/
@GetMapping("/download/downloadStdDictTemplate")
@ResponseBody
public void downloadStdDictTemplate(HttpServletRequest request,HttpServletResponse response) throws Exception{
log.info("调用/download/downloadStdDictTemplate");
standardDirectoryService.downloadStdDictTemplate(request,response);
}
}
service 层接口定义
public interface IStandardDirectoryService {
/**
* 下载标准数据Excel模板
*/
void downloadStdDictTemplate(HttpServletRequest request,HttpServletResponse response) throws Exception;
}
service 层定义
@Service
public class StandardDirectoryServiceImpl implements IStandardDirectoryService {
/**
* 下载标准数据Excel模板
*/
@Override
public void downloadStdDictTemplate(HttpServletRequest request, HttpServletResponse response) throws Exception{
/**
* 创建文件
*/
//文件名
String fileName = "标准化字典导入模板";
//设置表头
String sheetName="标准化字典信息";
//设置列头
String[] title = {"IMEI","EID","IMSI","ICCID","MSISDN"};
// 在内存中创建excel
XSSFWorkbook workBook = new XSSFWorkbook();
XSSFSheet sheet = workBook.createSheet(sheetName);
XSSFRow headRow = sheet.createRow(0);
for (int i = 0; i < title.length; i++) {
//设置列宽
sheet.setColumnWidth(i, 256*13);
XSSFCell cell = headRow.createCell(i);
// 添加样式
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
if (title[i] != null) {
cell.setCellValue(title[i]);
}
}
response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("utf-8"),"ISO-8859-1" )+ ".xls");
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("UTF-8");
OutputStream out = response.getOutputStream();
workBook.write(out);
if(out!=null){
out.flush();
}
out.close();
}
}