poi整合springboot超簡單入門例子
阿新 • • 發佈:2019-01-10
1.匯入依賴
2.application.properties只需要資料庫連線資訊就可以
3.目錄結構 有個沒用的service,請忽略
4.Controller,因為入門列子,所以簡單的匯出 匯入讀取資料都是可以的
貼上程式碼-》
package com.idress.action;
import com.idress.entity.User;
import com.idress.service.UserService;
import com.idress.utils.ExcelUtils;
import org.apache.poi.hpsf.DocumentSummaryInformation;
import org.apache.poi.hpsf.SummaryInformation;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Controller
public class ExcelController {
@Autowired
private UserService userService;
@RequestMapping("/")
public String toIndex(){
return "poi";
}
@RequestMapping("/excel/upload")
public String fileUpload(@RequestParam("file") MultipartFile file) throws IOException {
if(!ExcelUtils.validateExcel(file.getOriginalFilename())){
System.out.println("檔案必須是excel!");
return null;
}
long size=file.getSize();
if(file.getOriginalFilename()==null || file.getOriginalFilename().equals("") || size==0){
System.out.println("檔案不能為空");
return null;
}
HSSFWorkbook workbook = new HSSFWorkbook(new POIFSFileSystem(file.getInputStream()));
int numberOfSheets = workbook.getNumberOfSheets();//獲得有多少sheet
HSSFSheet sheet = workbook.getSheetAt(0);//預設只有一個sheet
int rows = sheet.getPhysicalNumberOfRows();//獲得sheet有多少行
//遍歷行
for (int j = 0; j < rows; j++) {
if (j == 0) {
continue;//標題行(省略)
}
HSSFRow row = sheet.getRow(j);
for (int k = 0; k < row.getPhysicalNumberOfCells(); k++) {
HSSFCell cell = row.getCell(k);
System.out.println(cell.toString());
}
}
return "poi";
}
//生成user表excel
@GetMapping(value = "/excel/getUser")
@ResponseBody
public String getUser(HttpServletResponse response) throws Exception{
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("統計表");
createTitle(workbook,sheet);
List<User> rows = new ArrayList<>();//userService.getAll();
rows.add(new User("1","小明","牛逼",new Date()));
rows.add(new User("2","中明","牛2逼",new Date()));
//設定日期格式
HSSFCellStyle style = workbook.createCellStyle();
style.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm"));
//新增資料行,並且設定單元格資料
int rowNum=1;
for(User user:rows){
HSSFRow row = sheet.createRow(rowNum);
row.createCell(0).setCellValue(user.getId());
row.createCell(1).setCellValue(user.getName());
row.createCell(2).setCellValue(user.getUsername());
HSSFCell cell = row.createCell(3);
cell.setCellValue(user.getCreate_time());
cell.setCellStyle(style);
rowNum++;
}
String fileName = "匯出excel例子.xls";
//生成excel檔案
buildExcelFile(fileName, workbook);
//瀏覽器下載excel
buildExcelDocument(fileName,workbook,response);
return "download excel";
}
//建立表頭
private void createTitle(HSSFWorkbook workbook,HSSFSheet sheet){
HSSFRow row = sheet.createRow(0);
//設定列寬,setColumnWidth的第二個引數要乘以256,這個引數的單位是1/256個字元寬度
sheet.setColumnWidth(1,12*256);
sheet.setColumnWidth(3,17*256);
//設定為居中加粗
HSSFCellStyle style = workbook.createCellStyle();
HSSFFont font = workbook.createFont();
font.setBold(true);
//style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
style.setFont(font);
HSSFCell cell;
cell = row.createCell(0);
cell.setCellValue("ID");
cell.setCellStyle(style);
cell = row.createCell(1);
cell.setCellValue("顯示名");
cell.setCellStyle(style);
cell = row.createCell(2);
cell.setCellValue("使用者名稱");
cell.setCellStyle(style);
cell = row.createCell(3);
cell.setCellValue("建立時間");
cell.setCellStyle(style);
}
//生成excel檔案
protected void buildExcelFile(String filename,HSSFWorkbook workbook) throws Exception{
FileOutputStream fos = new FileOutputStream(filename);
workbook.write(fos);
fos.flush();
fos.close();
}
//瀏覽器下載excel
protected void buildExcelDocument(String filename,HSSFWorkbook workbook,HttpServletResponse response) throws Exception{
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(filename, "utf-8"));
OutputStream outputStream = response.getOutputStream();
workbook.write(outputStream);
outputStream.flush();
outputStream.close();
}
}
實體類:
import java.util.Date;
public class User {
private String id;
private String name;
private String username;
private Date create_time;
public User() {
}
public User(String id, String name, String username, Date create_time) {
this.id = id;
this.name = name;
this.username = username;
this.create_time = create_time;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Date getCreate_time() {
return create_time;
}
public void setCreate_time(Date create_time) {
this.create_time = create_time;
}
}
上傳檔案用來讀取資料的html(使用了thymeleaf)
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<base th:href="${#httpServletRequest.getContextPath()+'/'}">
<meta charset="UTF-8">
<title>匯入Excel資料</title>
</head>
<body>
<h1>這是使用者資訊頁</h1>
<form action="excel/upload" method="post" enctype="multipart/form-data">
<input name="file" type="file" />
<input type="submit"/>
</form>
</body>
</html>