pom文件需要引入的jar包:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.15-beta2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.15-beta2</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
UserInfo.java
package com.qiaojun;
import lombok.Getter;
import lombok.Setter;
/**
*
* @author qiaojun
* @date 2019/10/11
*/
@Getter
@Setter
public class UserInfo {
private Integer id;
private String name;
private String sex;
private Integer age;
public UserInfo() {
}
public UserInfo(Integer id, String name, String sex, Integer age) {
this.id = id;
this.name = name;
this.sex = sex;
this.age = age;
}
}
FilePortUtil.java
package com.qiaojun;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.poi.hssf.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletResponse;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
public class FilePortUtil {
private static final Logger logger = LoggerFactory.getLogger(FilePortUtil.class);
/**
* 導出功能
* 注意:泛型T類字段名和containBean集合裏字段名字的一致性
*
* @param response
* @param title 表名
* @param headers 表頭
* @param list 數據集
* @param containBean 數據集類型字段
* @param <T>
* @throws Exception
*/
public static <T> void exportExcel(HttpServletResponse response, String title, String[] headers, List<T> list, List<String> containBean) throws Exception {
HSSFWorkbook workbook = null;
try {
workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet(title);
HSSFRow row = sheet.createRow(0);
//創建第一行表頭
for (short i = 0; i < headers.length; i++) {
HSSFCell cell = row.createCell(i);
HSSFRichTextString text = new HSSFRichTextString(headers[i]);
cell.setCellValue(text);
}
Iterator<T> it = list.iterator();
int index = 0;
while (it.hasNext()) {
index++;
row = sheet.createRow(index);
T t = (T) it.next();
//反射得到字段
Field[] fields = t.getClass().getDeclaredFields();
//如果需要匹配
if (CollectionUtils.isNotEmpty(containBean)) {
for (int j = 0; j < containBean.size(); j++) {
for (Field field : fields) {
if (!field.getName().equals(containBean.get(j))) {
continue;
}
//給每一列set值
setCellValue(t, field, row, j);
}
}
} else {
for (int i = 0; i < fields.length; i++) {
Field field = fields[i];
setCellValue(t, field, row, i);
}
}
}
//application/vnd.ms-excel告訴瀏覽器要下載的是個excel
response.setContentType("application/vnd.ms-excel;charset=UTF-8");
//請求頭設置,Content-Disposition爲下載標識,attachment標識以附件方式下載
response.addHeader("Content-Disposition", "attachment;filename=" + new String((title).getBytes(), "ISO8859-1") + ".xls");
workbook.write(response.getOutputStream());
} finally {
if (workbook != null) {
workbook.close();
}
}
}
/**
* 設置每一行中的列
*
* @param t
* @param field
* @param row
* @param index
* @param <T>
*/
private static <T> void setCellValue(T t, Field field, HSSFRow row, int index) {
HSSFCell cell = row.createCell(index);
Object value = invoke(t, field);
String textValue = null;
if (value != null) {
if (value instanceof Date) {
Date date = (Date) value;
textValue = DateFormatUtils.format(date, "yyyy-MM-dd HH:mm:ss");
} else {
textValue = value.toString();
}
}
if (textValue != null) {
cell.setCellValue(textValue);
}
}
/**
* 反射映射數據集字段
*
* @param t
* @param field
* @param <T>
* @return
*/
private static <T> Object invoke(T t, Field field) {
try {
String fieldName = field.getName();
PropertyDescriptor pd = new PropertyDescriptor(fieldName, t.getClass());
Method method = pd.getReadMethod();
return method.invoke(t);
} catch (Exception e) {
return null;
}
}
}
TestController.java
package com.qiaojun;
import com.qiaojun.UserInfo;
import com.qiaojun.FilePortUtil;
import org.apache.poi.ss.usermodel.*;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@Controller
@RequestMapping("/test")
public class TestController {
//導出
@RequestMapping("/exportExcle")
public void exportExcle(HttpServletResponse response){
//導出的表名
String title = "參數導出";
//表中第一行表頭字段
String[] headers = {"編號", "姓名", "性別"};
//實際數據結果集
List<UserInfo> listObject = new ArrayList<>();
listObject.add(new UserInfo(1,"張三","男",18));
listObject.add(new UserInfo(2,"李四","女",20));
listObject.add(new UserInfo(3,"王五","男",19));
//具體需要寫入excel需要哪些字段,這些字段取自UserReward類,也就是上面的實際數據結果集的泛型
List<String> listColumn = Arrays.asList("id", "name", "sex");
try {
FilePortUtil.exportExcel(response, title, headers, listObject, listColumn);
} catch (Exception e) {
e.printStackTrace();
}
}
//導入
@RequestMapping("/fileImport")
@ResponseBody
public String fileImport(HttpServletRequest request,MultipartFile fileName,MultipartFile fileName1){
// List<MultipartFile> files = ((MultipartHttpServletRequest)request).getFiles("file");
// for (MultipartFile file:files){
// if (file.getName().equals("file1")){
// System.out.println(fileImport(file));
//
// }
// }
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
MultipartFile file = multiRequest.getFile("fileName");
System.out.println(fileImport(file));
System.out.println("----------------------------");
MultipartFile file1 = multiRequest.getFile("fileName1");
System.out.println(fileImport(file));
System.out.println("----------------------------");
System.out.println(fileImport(fileName));
System.out.println("----------------------------");
System.out.println(fileImport(fileName1));
return "ok";
}
/**
* 導入功能
*/
public int fileImport(MultipartFile multipartFile) {
File file = null;
Workbook workbook = null;
int totalNum = 0;
//得到的path是 /D:/springbootdemo/target/springbootdemo/WEB-INF/classes/
String path = FilePortUtil.class.getClassLoader().getResource("/").getPath();
//拼接後的path就是 /D:/springbootdemo/target/springbootdemo/WEB-INF/xxx.xlsx
path = path.substring(0, path.indexOf("WEB-INF") + "WEB-INF".length()) + "/" + multipartFile.getOriginalFilename();
file = new File(path);
try {
//把文件流copy讀取到文件中
FileCopyUtils.copy(multipartFile.getBytes(), file);
workbook = WorkbookFactory.create(new FileInputStream(file));
//遍歷sheet頁
for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
Sheet sheet = workbook.getSheetAt(i);
if (sheet == null) {
continue;
}
//統計導入的總條數,包含表頭
if (sheet.getLastRowNum() > 0) {
totalNum += sheet.getLastRowNum();
}
//遍歷行,這裏j的初始值取1是因爲我的表格裏第一行是表頭
for (int j = 1; j < sheet.getPhysicalNumberOfRows(); j++) {
Row row = sheet.getRow(j);
//解析列,下標從0開始
Cell cell0 = row.getCell(0);
Cell cell1 = row.getCell(1);
Cell cell2 = row.getCell(2);
System.out.println(getCellValue(cell0)+","+getCellValue(cell1)+","+getCellValue(cell2));
//這裏添加自己的業務處理邏輯
}
}
//解析完刪除此路徑下的文件
file.delete();
return totalNum;
} catch (Exception e) {
e.printStackTrace();
}
return totalNum;
}
private String getCellValue(Cell cell) {
if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
return String.valueOf(cell.getBooleanCellValue());
} else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
Double d = cell.getNumericCellValue();
return String.valueOf(d.intValue());
}
return String.valueOf(cell.getStringCellValue());
}
}
test.jsp
<%@ page contentType="text/html; charset=utf-8" %>
<%
request.setAttribute("path",request.getContextPath());
%>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=8" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<a href="${path}/test/exportExcle">導出測試</a>
<form id="fileForm" enctype="multipart/form-data">
<input type="file" name="fileName" id="file">
<input type="file" name="fileName1" id="file1">
</form>
<input type="button" id="subForm" value="上傳">
<script type="text/javascript" src="${path}/js/jquery-1.8.3.min.js"></script>
<script>
$("#subForm").click(function () {
var FormDatas=new FormData($("#fileForm")[0]);
var fileName=$("#file").val();
alert(fileName);
$.ajax({
type:'post',
url:'${path}/test/fileImport',
async : false,
cache : false,
contentType : false,
processData : false,
data:FormDatas,
success: function(data){
alert("導入完成");
return false;
},
error : function(data){
}
});
});
</script>
</body>
</html>