引入poi依賴
<!-- poi 相關jar包 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
POI導出
@RestController
@RequestMapping("/poi")
public class PoiController {
@RequestMapping("/poiOut")
public void poiImport(HttpServletResponse response) throws IOException {
//新建excel文檔
HSSFWorkbook workbook = new HSSFWorkbook();
//字體樣式
HSSFFont font = workbook.createFont();
font.setColor(Font.COLOR_RED);
font.setBold(true);
//日期格式化
HSSFDataFormat dataFormat = workbook.createDataFormat();
short format = dataFormat.getFormat("yyyy-MM-dd");
//標題單元格樣式
HSSFCellStyle cellStyle = workbook.createCellStyle();
cellStyle.setFont(font);
cellStyle.setAlignment(HorizontalAlignment.CENTER);
//內容單元格樣式
HSSFCellStyle cellStyle1 = workbook.createCellStyle();
cellStyle1.setDataFormat(format);
//創建excel工作表
HSSFSheet sheet = workbook.createSheet("aaa");
sheet.setColumnWidth(3,40*256); //必須乘於256
//創建行
HSSFRow row = sheet.createRow(0);
String[] arr = {"ID","文章標題","文章描述","創建時間","熱度"};
for (int i=0;i<arr.length;i++) {
HSSFCell cell = row.createCell(i);
cell.setCellValue(arr[i]);
cell.setCellStyle(cellStyle);
}
List<Article> list = new ArrayList<Article>();
list.add(new Article("001","HTML5","文章沒有內容,就是湊字數",new Date(),1));
list.add(new Article("002","HTML5","文章沒有內容,就是湊字數",new Date(),2));
list.add(new Article("003","HTML5","文章沒有內容,就是湊字數",new Date(),3));
list.add(new Article("004","HTML5","文章沒有內容,就是湊字數",new Date(),4));
for (int i=0;i<list.size();i++) {
HSSFRow row1 = sheet.createRow(i + 1);
row1.createCell(0).setCellValue(list.get(i).getId());
row1.createCell(1).setCellValue(list.get(i).getTitle());
row1.createCell(2).setCellValue(list.get(i).getDescription());
HSSFCell cell = row1.createCell(3);
cell.setCellValue(list.get(i).getCreateTime());
cell.setCellStyle(cellStyle1);
row1.createCell(4).setCellValue(list.get(i).getHotValue());
}
//web瀏覽通過MIME類型判斷文件是excel類型
response.setContentType("application/vnd.ms-excel;charset=utf-8");
response.setCharacterEncoding("utf-8");
// 對文件名進行處理。防止文件名亂碼
String fileName = URLEncoder.encode("合同.xls", "UTF-8");
// Content-disposition屬性設置成以附件方式進行下載
response.setHeader("Content-disposition", "attachment;filename=" + fileName);
OutputStream os = response.getOutputStream();
workbook.write(os);
os.flush();
os.close();
}
}
POI導入