導入依賴包
```java
compile 'com.alibaba:easyexcel:2.2.6'
```
代碼(依賴於springboot)
提供數據導入接口
```java
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.alibaba.excel.EasyExcel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
@Api(value="用戶導入相關接口",tags= {"UserImport API"})
@RestController
@RequestMapping("/api/uc/import")
public class UcImportRs {
public static Logger logger = LoggerFactory.getLogger(UcImportRs.class);
String path;
@Autowired(required=false)
UcService _ucService;
/**
* 文件上傳類
* 文件會自動綁定到MultipartFile中
* @param request 獲取請求信息
* @param description 文件描述
* @param file 上傳的文件
* @return 上傳成功或失敗結果
* @throws IOException
* @throws IllegalStateException
*/
@ApiOperation(value="excel文件上傳")
@RequestMapping(value = "/uploadExcel",method = {RequestMethod.POST})
public String upload(HttpServletRequest request, @RequestParam("file") MultipartFile file) throws IllegalStateException, IOException {
// 測試MultipartFile接口的各個方法
System.out.println("文件類型ContentType=" + file.getContentType());
System.out.println("文件組件名稱Name=" + file.getName());
System.out.println("文件原名稱OriginalFileName=" + file.getOriginalFilename());
System.out.println("文件大小Size=" + file.getSize()/1024 + "KB");
// 如果文件不為空,寫入上傳路徑,進行文件上傳
if (!file.isEmpty()) {
//String restult = importUc(file.getInputStream());
// 構建上傳文件的存放路徑
System.out.println("path = " + path);
// 獲取上傳的文件名稱,並結合存放路徑,構建新的文件名稱
String filename = file.getOriginalFilename();
File filepath = new File(path, filename);
// 判斷路徑是否存在,不存在則新創建一個
if (!filepath.getParentFile().exists()) {
filepath.getParentFile().mkdirs();
}
// 將上傳文件保存到目標文件目錄
file.transferTo(new File(path + File.separator + filename));
logger.debug("文件上傳成功:路徑:{},開始導入用戶",filepath.getAbsolutePath());
String result = importUc(filepath);
return result;
} else {
return "error";
}
}
//導入用戶
public String importUc(InputStream in) {
UserDataListener listener = new UserDataListener();
EasyExcel.read(in, UserData.class,listener).sheet().doRead();
List<UserData> datas = listener.getDatas();
return _ucService.addUc(datas);
}
//導入用戶
public String importUc(File filepath) {
UserDataListener listener = new UserDataListener();
EasyExcel.read(filepath.getAbsolutePath(), UserData.class,listener).sheet().doRead();
List<UserData> datas = listener.getDatas();
return _ucService.addUc(datas);
}
@ApiOperation(value="獲取用戶信息導入模板")
@RequestMapping(value = "/getExcelTemplate",method = {RequestMethod.GET})
public void download( HttpServletRequest request, HttpServletResponse response) throws Exception {
try (
InputStream inputStream = new FileInputStream(new File("./config/用戶信息導入表.xlsx"));
OutputStream outputStream = response.getOutputStream();
)
{
String fileName = java.net.URLEncoder.encode("用戶信息導入表.xlsx", "UTF8");
response.setCharacterEncoding("UTF-8");
response.setContentType("application/x-download;charset=utf8");
response.addHeader("Content-Disposition", "attachment;filename="+fileName);
IOUtils.copy(inputStream, outputStream);
outputStream.flush();
}
}
public ResponseEntity<FileSystemResource> getExcelTemplate() throws Throwable {
File file = new File("./config/用戶信息導入表.xlsx");
return export(file);
}
public ResponseEntity<FileSystemResource> export(File file) {
if (file == null) {
return null;
}
HttpHeaders headers = new HttpHeaders();
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
headers.add("Content-Disposition", "attachment; filename=用戶信息導入模板.xlsx");
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
headers.add("Last-Modified", new Date().toString());
headers.add("ETag", String.valueOf(System.currentTimeMillis()));
return ResponseEntity
.ok()
.headers(headers)
.contentLength(file.length())
.contentType(MediaType.parseMediaType("application/octet-stream"))
.body(new FileSystemResource(file));
}
}
```
監聽類:
```css
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.dubbo.common.json.JSON;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.CellExtra;
public class UserDataListener extends AnalysisEventListener<UserData> {
public static Logger LOGGER = LoggerFactory.getLogger(UserDataListener.class);
private List<UserData> datas = new ArrayList<>();
public List<UserData> getDatas() {
return datas;
}
public void setDatas(List<UserData> datas) {
this.datas = datas;
}
@Override
public void invoke(UserData data, AnalysisContext context) {
//當前行
LOGGER.debug("掃描到用戶:{}",data.getUserName());
if (data != null) {
datas.add(data);
}
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
System.out.println("解析結束");
}
/**
* 這里會一行行的返回頭
*
* @param headMap
* @param context
*/
@Override
public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
/*try {
System.out.println("解析到一條頭數據:{}" + JSON.json(headMap));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
}
@Override
public void extra(CellExtra extra, AnalysisContext context) {
try {
System.out.println("讀取到了一條額外信息:{}"+ JSON.json(extra));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
switch (extra.getType()) {
case COMMENT:
LOGGER.info("額外信息是批注,在rowIndex:{},columnIndex;{},內容是:{}", extra.getRowIndex(), extra.getColumnIndex(),
extra.getText());
break;
case HYPERLINK:
if ("Sheet1!A1".equals(extra.getText())) {
LOGGER.info("額外信息是超鏈接,在rowIndex:{},columnIndex;{},內容是:{}", extra.getRowIndex(), extra.getColumnIndex(),
extra.getText());
} else if ("Sheet2!A1".equals(extra.getText())) {
LOGGER.info(
"額外信息是超鏈接,而且覆蓋了一個區間,在firstRowIndex:{},firstColumnIndex;{},lastRowIndex:{},lastColumnIndex:{},"
+ "內容是:{}",
extra.getFirstRowIndex(), extra.getFirstColumnIndex(), extra.getLastRowIndex(),
extra.getLastColumnIndex(), extra.getText());
} else {
}
break;
case MERGE:
LOGGER.info("額外信息是合並單元格,而且覆蓋了一個區間,在firstRowIndex:{},firstColumnIndex;{},lastRowIndex:{},lastColumnIndex:{}",
extra.getFirstRowIndex(), extra.getFirstColumnIndex(), extra.getLastRowIndex(),
extra.getLastColumnIndex());
break;
default:
}
}
}
```
模型:
```java
import com.alibaba.excel.annotation.ExcelIgnore;
import com.alibaba.excel.annotation.ExcelProperty;
public class UserData {
@ExcelProperty("一級部門")
private String depatment1Name;
@ExcelProperty("二級部門")
private String depatment2Name;
@ExcelProperty("用戶名")
private String userName;
@ExcelProperty("用戶ID")
private String userId;
@ExcelProperty("電話")
private String telphone;
}
```
userService:
```java
@Component
public class UcService {
public String addUc(List<UserData> datas) {
//do something
}
}
```
以上!