org.apache.poi
poi
3.10-FINAL
org.apache.poi
poi-ooxml
3.10-FINAL
test
和数据表 user
及相关测试数据
CREATE DATABASE `test` DEFAULT CHARSET utf8;
CREATE TABLE `user` (
`id` int(20) NOT NULL AUTO_INCREMENT,
`name` varchar(20) DEFAULT NULL,
`age` int(20) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;
user
数据表字段对应
import java.io.Serializable;
public class User implements Serializable {
private static final long serialVersionUID = 8755803182642361875L;
private Long id;
private Long age;
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getAge() {
return age;
}
public void setAge(Long age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
/**
* User的数据访问接口 UserDao.java
*/
import com.test.web2.entity.User;
import java.util.List;
public interface UserDao {
void create(List users);
}
/**
* 实现类 UserDaoImpl.java
*/
import com.test.web2.dao.UserDao;
import com.test.web2.entity.User;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public class UserDaoImpl implements UserDao {
@Autowired
private SqlSession sqlSession;
static final String MAPPER = "com.test.web2.UserMapper.";
@Override
public void create(final List users) {
sqlSession.insert(MAPPER + "create", users);
}
}
INSERT INTO
`user`
(`id`,`name`,`age`)
VALUES
(
#{item.id},
#{item.name},
#{item.age}
)
public class ExcelUtil {
/** 版本2007*/
public final static String XLSX = "xlsx";
public List> readXlsx(final String path) throws Exception {
final InputStream is = new FileInputStream(path);
final XSSFWorkbook xssfWorkbook = new XSSFWorkbook(is);
final List> result = new ArrayList<>();
for (XSSFSheet xssfSheet : xssfWorkbook) {
if (xssfSheet == null) {
continue;
}
for (int rowNum = 1; rowNum <= xssfSheet.getLastRowNum(); rowNum++) {
final XSSFRow xssfRow = xssfSheet.getRow(rowNum);
final int minColIx = xssfRow.getFirstCellNum();
final int maxColIx = xssfRow.getLastCellNum();
final List rowList = new ArrayList<>();
for (int colIx = minColIx; colIx < maxColIx; colIx++) {
final XSSFCell cell = xssfRow.getCell(colIx);
if (cell == null) {
continue;
}
rowList.add(cell.toString());
}
result.add(rowList);
}
}
return result;
}
/** 版本2003*/
public final static String XLS = "xls";
public List> readXls(final String path) throws Exception {
final InputStream is = new FileInputStream(path);
final HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is);
final List> result = new ArrayList<>();
final int size = hssfWorkbook.getNumberOfSheets();
for (int numSheet = 0; numSheet < size; numSheet++) {
final HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
if (hssfSheet == null) {
continue;
}
for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
final HSSFRow hssfRow = hssfSheet.getRow(rowNum);
final int minColIx = hssfRow.getFirstCellNum();
final int maxColIx = hssfRow.getLastCellNum();
final List rowList = new ArrayList<>();
for (int colIx = minColIx; colIx < maxColIx; colIx++) {
final HSSFCell cell = hssfRow.getCell(colIx);
if (cell == null) {
continue;
}
rowList.add(getStringVal(cell));
}
result.add(rowList);
}
}
return result;
}
public static String getStringVal(final HSSFCell cell) {
switch (cell.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
return cell.getBooleanCellValue() ? "TRUE" : "FALSE";
case Cell.CELL_TYPE_FORMULA:
return cell.getCellFormula();
case Cell.CELL_TYPE_NUMERIC:
cell.setCellType(Cell.CELL_TYPE_STRING);
return cell.getStringCellValue();
case Cell.CELL_TYPE_STRING:
return cell.getStringCellValue();
default:
return "";
}
}
}
@Controller
public class UserController {
@Autowired
private UserDao userDao;
/**
* 上传 Excel文件批量导入用户信息 支持 [.xlsx/ .xls] 两种分别是 版本2007/ 版本2003
* */
@PostMapping("/importUsersExcelFile")
public @ResponseBody Map importUsersExcelFile(@RequestParam("file") MultipartFile[] multfiles) {
final Map resp = new HashMap<>();
/** 上传文件数*/
final int fileCount = multfiles.length;
if (fileCount == 0) {
resp.put("message", "请选择文件!");
}
String lastFilePath;
final List allRows = new ArrayList<>();
for (int i = 0; i < fileCount; i++) {
/** 源文件名称*/
final String originalFileName = multfiles[i].getOriginalFilename();
if (StringUtils.isBlank(originalFileName) || (!originalFileName.endsWith(ExcelUtil.XLS) && !originalFileName.endsWith(ExcelUtil.XLSX))) {
continue;
}
/** 文件后缀*/
final String suffix = originalFileName.substring(originalFileName.lastIndexOf("."));
final String newFileName = String.valueOf(System.currentTimeMillis() + suffix);
/** 今天日期(用于文件名)*/
final String date = DateTimeFormatter.ofPattern("yyyy-MM-dd").format(LocalDateTime.now());
final String relativePath = File.separator + date;
final String filePath = "D:\\file" + relativePath;
final File targetFile = new File(filePath);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
FileOutputStream out = null;
try {
lastFilePath = filePath + File.separator + newFileName;
out = new FileOutputStream(lastFilePath);
out.write(multfiles[i].getBytes());
List> result;
if (originalFileName.endsWith(ExcelUtil.XLS)) {
result = new ExcelUtil().readXls(lastFilePath);
} else {
result = new ExcelUtil().readXlsx(lastFilePath);
}
for (int i2 = 0; i2 < result.size(); i2++) {
final List model = result.get(i2);
final User user = new User();
/** 用户编号*/
final Long id = Long.parseLong(model.get(0));
user.setId(id);
/** 用户称呼*/
user.setName(model.get(1));
/** 用户年龄*/
final Long age = Long.parseLong(model.get(2));
user.setAge(age);
allRows.add(user);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
if (allRows.isEmpty()) {
resp.put("message", "导入失败!");
} else {
userDao.create(allRows);
}
resp.put("message", "导入成功!");
return resp;
}
}
如果您觉得有帮助,欢迎点赞哦 ~ 谢谢!!