对于excel上传,我们需要做几方面的配置,包括jsp,springmvc.xml,pom.xml,controller中做相关配置,对于excel的格式还有xls和xlsx的区别,所以,我采用的是jxl--xls,poi--xlsx,下面的是相关配置
pom.xml
commons-fileupload
commons-fileupload
1.2.1
commons-io
commons-io
2.4
net.sourceforge.jexcelapi
jxl
2.6.12
org.apache.poi
poi
3.10.1
org.apache.poi
poi-ooxml
3.8
org.apache.poi
poi-ooxml-schemas
3.8
jsp
在jsp中要引入:ajaxfileupload.js 下载
js//向后台上传Excel数据
function ajaxFileUpload() {
debugger;
var fileName = $("#file").val();
if(fileName==null || fileName==""){
alert("请选择文件!");
return;
}
var fileSuffixArray = fileName.split('.');
if(!(fileSuffixArray[1] == 'xls' || fileSuffixArray[1] == 'xlsx')){
alert("文件格式错误,请上传Excel文件!");
return;
}
var url = "<%=path%>/data/uploadExcelData";
var method = "method=fileUpload"
$.ajaxFileUpload({
url : url,
secureuri : false,
fileElementId : 'file',
dataType : 'text',
success : function(data, status) {
if (data == "exist") {
alert("该文件已经存在请勿重复上传");
}
if (data == "success") {
alert("文件上传成功");
}
if (data == "fail") {
alert("文件上传失败,请重新上传");
}
},
error : function() {
}
});
}
springmvc.xml
controller
public ModelAndView uploadExcelData(HttpServletRequest request,MultipartFile file) throws IOException{
try {
String filename = file.getOriginalFilename();
String[] split = filename.split("\\.");
if("xls".equals(split[1])) {
ExcelUtil.excelToData(file);
}else if("xlsx".equals(split[1])) {
ExcelUtil.excelToDataNew(file);
}
} catch (Exception e) {
e.printStackTrace();
}
ModelAndView md = new ModelAndView();
return md;
}
}
ExcelUtil
/**
* @Description 将excel变为实体类对象集合:(.xls)
* 1: 想使用时,直接将它赋值到相应位置,将1和2和3补齐即可
* 2: excel需要使用特定版本的,2003的好用(其余未验证)
* 3: 此方法不可直接调用,使用时需要将核心代码复制到相应位置使用
* @param request
* @param file
* @return
* @throws IOException
* @throws BiffException
*/
public static List excelToData(MultipartFile file) throws IOException, BiffException{
List list = new ArrayList();
//获取输入流
InputStream in = file.getInputStream();
// 创建一个新的写入工作簿
Workbook book = Workbook.getWorkbook(in);
//获取第一个sheet页
Sheet sheet = book.getSheet(0);
//获取Sheet表中所包含的总列数
int rsColumns = sheet.getColumns();
//获取Sheet表中所包含的总行数
int rsRows = sheet.getRows();
//获取指定单元格的对象引用
for(int i=1;i> list = new ArrayList>();
// IO流读取文件
InputStream input = null;
XSSFWorkbook wb = null;
ArrayList rowList = null;
try {
input = file.getInputStream();
// 创建文档
wb = new XSSFWorkbook(input);
//读取sheet(页)
for(int numSheet=0;numSheet();
int totalCells = xssfRow.getLastCellNum();
//读取列,从第一列开始
for(int c=0;c<=totalCells+1;c++){
XSSFCell cell = xssfRow.getCell(c);
if(cell==null){
//当cell值为null时如何处理
// rowList.add(ExcelUtil.EMPTY);
continue;
}
//当cell值不为null时如何处理
// rowList.add(ExcelUtil.getXValue(cell).trim());
}
list.add(rowList);
}
}
}
return list;
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}