0.准备工作
1.上传文件代码查看本人之前的博客:
https://blog.youkuaiyun.com/qq_37067955/article/details/85338375
1.编写excel读取的util的工具
#ReadExcel.java
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.springframework.web.context.request.NativeWebRequest;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
public class ReadExcel {
public void excel(String fileUrl) throws Exception {
//不支持Excel2007格式(也就是xlsx格式文件)
File file = new File(fileUrl);
Workbook wb = Workbook.getWorkbook(file);
Sheet[] sheets = wb.getSheets();
//遍历每页
for(Sheet s : sheets){
System.out.println(s.getName() + " : ");
int rows = s.getRows();
if(rows > 0){
//遍历每行
for(int i = 2 ;i < rows ; i++){
System.out.print("行" + i + " : ");
Cell[] cells = s.getRow(i);
if(cells.length > 0){
//遍历每行中的每列
String str = "";
for(Cell c : cells){
str = c.getContents().trim();//此处是获取到的每个单元格的内容,可以在此进行操作
System.out.print(str + ";");
}
System.out.println();
}
}
}
}
}
}
3 工具类的调用(在controller中调用)
@RequestMapping(value="upload",method=RequestMethod.POST)
@ResponseBody
public String upload(MultipartFile file,HttpServletRequest request) throws IOException{
String path = request.getSession().getServletContext().getRealPath("upload");
String fileName = file.getOriginalFilename();
File dir = new File(path,fileName);
if(!dir.exists()){
dir.mkdirs();
}
file.transferTo(dir);
ReadExcel readExcel = new ReadExcel();
try {
System.out.println(path+"\\"+fileName);
readExcel.excel(path+"\\"+fileName);// 此处调用工具类,需要传一个excel的文件的路径
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return fileName;
}