用的是poi框架 先贴maven配置
<dependency>
<groupId>org.apache.poigroupId>
<artifactId>poiartifactId>
<version>4.0.1version>
dependency>
<dependency>
<groupId>org.apache.poigroupId>
<artifactId>poi-ooxmlartifactId>
<version>4.0.1version>
dependency>
前端表格+逻辑:
<form id="fileForm" action="/upload" method="POST" enctype="multipart/form-data">
<input id="file" type="file" name="file" class="btn btn-outline-primary"/>
<input id="btnSubmitFile" type="button" value="upload file to /upload"/>
form>
JavaScript对应代码
<script type="text/javascript">
$(function () {
$("#btnSubmitFile").click(function () {
var form = new FormData(document.getElementById("fileForm"));
$.ajax({
url: "/upload",
type: "post",
data: form,
processData: false,
contentType: false,
success: function(data) {
$("#outputDiv").html(data);
},
error: function(e) {
console.log(e);
}
});
});
});
</script>
controller层
/**
* 上传excel保存在本地并加载
* @param file
* @return
* @throws IOException
* @throws InvalidFormatException
*/
@PostMapping("/upload")
@ResponseBody
public String upload(@RequestParam("file") MultipartFile file) throws IOException, InvalidFormatException {
if (file.isEmpty()) {
return "上传失败,请选择文件";
}
//加载文件至数据库并保存到本地
String fileName = file.getOriginalFilename();
String dir=System.getProperty("user.dir");
String destFileName=dir+ File.separator +"uploadedfiles_"+fileName;
System.out.println(destFileName);
File destFile = new File(destFileName);
file.transferTo(destFile);
broadbandDao.loadBroadExcel(destFileName);
return "到你想回到的界面或者改函数类型为void";
}
Dao层
/**
* 加载账号文件至数据库
* 2020/8/5
* @param excelFileName
*/
public void loadBroadExcel(String excelFileName)
{
String sql="INSERT INTO `broadband_account`(broad_username,broad_password,broad_cost) VALUES(?,?,?)"; //笔者的业务 无需理解
// 读取Excel文件内容
List<Broadband> readResult = BroadExcelReader.readExcel(excelFileName); //重点 相关代码在下一段
Iterator<Broadband> iterator=readResult.iterator(); //笔者的业务 无需理解
while (iterator.hasNext()) //笔者的业务 无需理解
{
Broadband broadband = iterator.next();
jdbcTemplate.update(sql,
broadband.getBroadUsername(),
broadband.getBroadPassword(),
broadband.getBroadCost());
}
}
BroadExcelReade.java (加载EXCEL数据类)
public class BroadExcelReader {
private static Logger logger = Logger.getLogger(BroadExcelReader.class.getName()); // 日志打印类
private static final String XLS = "xls";
private static final String XLSX = "xlsx";
/**
* 根据文件后缀名类型获取对应的工作簿对象
* @param inputStream 读取文件的输入流
* @param fileType 文件后缀名类型(xls或xlsx)
* @return 包含文件数据的工作簿对象
* @throws IOException
*/
public static Workbook getWorkbook(InputStream inputStream, String fileType) throws IOException {
Workbook workbook = null;
if (fileType.equalsIgnoreCase(XLS)) {
workbook = new HSSFWorkbook(inputStream);
} else if (fileType.equalsIgnoreCase(XLSX)) {
workbook = new XSSFWorkbook(inputStream);
}
return workbook;
}
/**
* 读取Excel文件内容
* @param fileName 要读取的Excel文件所在路径
* @return 读取结果列表,读取失败时返回null
*/
public static List<Broadband> readExcel(String fileName) {
Workbook workbook = null;
FileInputStream inputStream = null;
try {
// 获取Excel后缀名
String fileType = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
// 获取Excel文件
File excelFile = new File(fileName);
if (!excelFile.exists()) {
logger.warning("指定的Excel文件不存在!");
return null;
}
// 获取Excel工作簿
inputStream = new FileInputStream(excelFile);
workbook = getWorkbook(inputStream, fileType);
// 读取excel中的数据
List<Broadband> resultDataList = parseExcel(workbook);
return resultDataList;
} catch (Exception e) {
logger.warning("解析Excel失败,文件名:" + fileName + " 错误信息:" + e.getMessage());
return null;
} finally {
try {
if (null != workbook) {
workbook.close();
}
if (null != inputStream) {
inputStream.close();
}
} catch (Exception e) {
logger.warning("关闭数据流出错!错误信息:" + e.getMessage());
return null;
}
}
}
/**
* 解析Excel数据
* @param workbook Excel工作簿对象
* @return 解析结果
*/
private static List<Broadband> parseExcel(Workbook workbook) {
List<Broadband> resultDataList = new ArrayList<>();
// 解析sheet
for (int sheetNum = 0; sheetNum < workbook.getNumberOfSheets(); sheetNum++) {
Sheet sheet = workbook.getSheetAt(sheetNum);
// 校验sheet是否合法
if (sheet == null) {
continue;
}
// 获取第一行数据
int firstRowNum = sheet.getFirstRowNum();
Row firstRow = sheet.getRow(firstRowNum);
if (null == firstRow) {
logger.warning("解析Excel失败,在第一行没有读取到任何数据!");
}
// 解析每一行的数据,构造数据对象
int rowStart = firstRowNum ; //+1可以忽略第一行 不加就从第0行开始
int rowEnd = sheet.getPhysicalNumberOfRows();
for (int rowNum = rowStart; rowNum < rowEnd; rowNum++) {
Row row = sheet.getRow(rowNum);
if (null == row) {
continue;
}
Broadband resultData = convertRowToData(row);
if (null == resultData) {
logger.warning("第 " + row.getRowNum() + "行数据不合法,已忽略!");
continue;
}
resultDataList.add(resultData);
}
}
return resultDataList;
}
/**
* 将单元格内容转换为字符串
* @param cell
* @return
*/
private static String convertCellValueToString(Cell cell) {
if(cell==null){
return null;
}
String returnValue = null;
switch (cell.getCellType()) {
case NUMERIC: //数字
Double doubleValue = cell.getNumericCellValue();
// 格式化科学计数法,取一位整数
DecimalFormat df = new DecimalFormat("0");
returnValue = df.format(doubleValue);
break;
case STRING: //字符串
returnValue = cell.getStringCellValue();
break;
case BOOLEAN: //布尔
Boolean booleanValue = cell.getBooleanCellValue();
returnValue = booleanValue.toString();
break;
case BLANK: // 空值
break;
case FORMULA: // 公式
returnValue = cell.getCellFormula();
break;
case ERROR: // 故障
break;
default:
break;
}
return returnValue;
}
private static Broadband convertRowToData(Row row) {
Broadband resultData = new Broadband();
Cell cell;
int cellNum = 0;
cell = row.getCell(cellNum++);
String busername=convertCellValueToString(cell); //获取第一格内容
resultData.setBroadUsername(busername);
// 获取密码
cell = row.getCell(cellNum++); //下一列
String password=convertCellValueToString(cell); //获取第二格内容
resultData.setBroadPassword(password);
//获取费用
cell = row.getCell(cellNum++); //下一列
Integer cost= Integer.parseInt(convertCellValueToString(cell)); //获取第三格内容 往后的递推一样
resultData.setBroadCost(cost);
return resultData;
}
}
我的后台长这样
偷懒用的别人的bootstrap框架(捂脸)上面的上传文件也是别人的代码东拼西凑整合出来的(再次捂脸)
前段搜索栏代码+逻辑
<input id="search-input" class="form-control form-control-dark w-100" type="text" placeholder="Search" aria-label="Search" th:placeholder="${activeUri=='broadbands'?'搜索宽带账号':'搜索学生姓名'}">
<ul class="navbar-nav px-3">
<li class="nav-item text-nowrap">
<a id="btn-search" class="nav-link" href="#" >搜索a>
li>
ul>
$("#btn-search").click(function () {
var keyword=$("#search-input").val();
$("#search").attr("action","/broadbands"+keyword).submit();
})
后端controller
/**
*
* @param model
* @return
*/
@GetMapping("/broadbands{keyword}")
public String broadbandList(@PathVariable("keyword") String keyword, HttpServletRequest request,Model model)
{
//直接使用参数keyword就是搜索框内传来的关键字
//这部分的逻辑代码就要根据自身业务根据关键字实现自己的搜索功能
//就是利用keyword到数据库进行一个like查找 再返回结果封装成bean到前端给thymeleaf解析
}