編程思路:
- 前端input讀取xls、xlsx的Excel文件;
- 使用js的formData封裝文件和其他數據;
- 使用ajax請求發送到後臺,注意:contentType和processData要設置成false;
- 後臺使用MultipartFile接收文件,使用Workbook、Sheet、Row、Cell解析Excel;
- 使用ArrayList<ArrayList<Object>>接收數據,解析完畢。
引入依賴
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<!--解析json的jar包-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.10</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<!--接收Excel對象使用-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.0.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<!--解析Excel對象使用-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.0.0</version>
</dependency>
前端頁面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Excel</title>
<script type="text/javascript" src="/demo/lib/jquery-3.4.1.min.js"></script>
</head>
<body>
<input type="file" id="file"><button id="submit">提交</button>
</body>
</html>
<script type="text/javascript">
$("#submit").click(function(){
var str="我是一個字符串"; //定義字符串
var array=["我","是","數","組"]; //定義數組
var file=$("#file").get(0).files[0]; //定義並獲取文件,get(0)是將jquery對象轉換爲js對象,files[0]是獲取這個文件。0代表第一個文件,由於只傳了一個文件所以下標爲0
var formData=new FormData();
formData.append("str",str);
formData.append("array",JSON.stringify(array));
formData.append("file",file);
$.ajax({
url:"/demo/index/analysisExcel",
type:"post",
data:formData,
contentType:false,
processData:false,
success:function (data) {
alert(data);
},
error:function () {
alert("error");
}
});
});
</script>
注意:"contentType:false"和"processData:false"絕對不能少,不然會無法傳遞文件
後臺java解析代碼
package com.example.demo.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
/**
* @Description TODO
* @Author wangs
* @Date 2019/12/311:16
*/
@Controller
@RequestMapping("/index/")
public class IndexController {
@RequestMapping("toExcelPage")
public String toExcelPage(){
return "web/excel";
}
@RequestMapping("analysisExcel")
@ResponseBody
public String analysisExcel(MultipartFile file,String str,String array){ //注意和前端名字保持一致
ObjectMapper objectMapper =new ObjectMapper();
String nativeStr =str; //獲取字符串
try {
List<String> arrayList =(List)objectMapper.readValue(array, List.class); //讀取前端數組存在list中
InputStream inputStream =file.getInputStream();//獲取前端傳遞過來的文件對象,存儲在“inputStream”中
String fileName = file.getOriginalFilename();//獲取文件名
Workbook workbook =null; //用於存儲解析後的Excel文件
//判斷文件擴展名爲“.xls還是xlsx的Excel文件”,因爲不同擴展名的Excel所用到的解析方法不同
String fileType = fileName.substring(fileName.lastIndexOf("."));
if(".xls".equals(fileType)){
workbook= new HSSFWorkbook(inputStream);//HSSFWorkbook專門解析.xls文件
}else if(".xlsx".equals(fileType)){
workbook = new XSSFWorkbook(inputStream);//XSSFWorkbook專門解析.xlsx文件
}
ArrayList<ArrayList<Object>>list =new ArrayList<>();
Sheet sheet; //工作表
Row row; //行
Cell cell; //單元格
//循環遍歷,獲取數據
for(int i=0;i<workbook.getNumberOfSheets();i++){
sheet=workbook.getSheetAt(i);//獲取sheet
for(int j=sheet.getFirstRowNum();j<=sheet.getLastRowNum();j++){//從有數據的第行開始遍歷
row=sheet.getRow(j);
if(row!=null&&row.getFirstCellNum()!=j){ //row.getFirstCellNum()!=j的作用是去除首行,即標題行,如果無標題行可將該條件去掉
ArrayList tempList =new ArrayList();
for(int k=row.getFirstCellNum();k<row.getLastCellNum();k++){//這裏需要注意的是getLastCellNum()的返回值爲“下標+1”
cell =row.getCell(k);
tempList.add(cell);
}
list.add(tempList);
}
}
}
System.out.println("我是讀取的字符串:"+nativeStr);
System.out.println("我是讀取的數組:"+arrayList.toString());
System.out.println("我是解析的Excel:"+list.toString());
} catch (IOException e) {
e.printStackTrace();
}
return "success";
}
}
進入頁面,選擇文件,點擊提交
Excel中的的內容:
後臺解析結果
成功!