需要注意的问题:
导入的数据存在很多不确定因素,所以要根据自己的业务需要做好相应的判断,是不是null,格式对不对,数据量等等、、、
首先,需要一个type=file和form
<form id="fileForm" name="uploadForm" action="***" style="display: inline-block;" method="post" enctype="multipart/form-data">
<a id="***"
href="javascript:void(0)" class="easyui-linkbutton file"
iconCls="icon-edit" plain="true">
<input type="file" name="file" id="file" οnchange="uploadTemplate();" accept=".xls,.xlsx">一键发货
</a>
</form>
改变文件选择样式(可以不要)
.file {
position: relative;
display: inline-block;
}
.file input {
position: absolute;
right: 0;
top: 0;
opacity: 0;
}
提交之前注意一下,onChange不刷新浏览器只能执行一次,想多次执行可以设置如下:
function uploadTemplate() {
$("#file").val("");
}
后台:
@RequestMapping(value="***", method = { RequestMethod.POST })
@ResponseBody
public HttpJsonResult<Integer> fileUpload(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request){
List<T> result = new ArrayList<T>();
InputStream is=file.getInputStream();
BufferedInputStream in = new BufferedInputStream(is);
POIFSFileSystem fs = new POIFSFileSystem(in);
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFCell cell = null;
for (int sheetIndex = 0; sheetIndex < wb.getNumberOfSheets(); sheetIndex++) {
HSSFSheet st = wb.getSheetAt(sheetIndex);
// 第一行为标题,不取
for (int rowIndex = 1; rowIndex <= st.getLastRowNum(); rowIndex++) {
HSSFRow row = st.getRow(rowIndex);
if (row == null) {
continue;
}
boolean hasValue = false;
//实体对象
for (short columnIndex = 0; columnIndex < row.getLastCellNum(); columnIndex++) {
String value = "";
cell = row.getCell(columnIndex);
if (cell != null) {
switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_STRING:
value = cell.getStringCellValue();
break;
case HSSFCell.CELL_TYPE_NUMERIC:
if (HSSFDateUtil.isCellDateFormatted(cell)) {
Date date = cell.getDateCellValue();
if (date != null) {
value = new SimpleDateFormat("yyyy-MM-dd")
.format(date);
} else {
value = "";
}
} else {
value = new DecimalFormat("0").format(cell
.getNumericCellValue());
}
break;
case HSSFCell.CELL_TYPE_FORMULA:
// 导入时如果为公式生成的数据则无值
if (!cell.getStringCellValue().equals("")) {
value = cell.getStringCellValue();
} else {
value = cell.getNumericCellValue() + "";
}
break;
case HSSFCell.CELL_TYPE_BLANK:
break;
case HSSFCell.CELL_TYPE_ERROR:
value = "";
break;
case HSSFCell.CELL_TYPE_BOOLEAN:
value = (cell.getBooleanCellValue() == true ? "Y"
: "N");
break;
default:
value = "";
}
}
//没有数据
if (columnIndex == 0 && value.trim().equals("")) {
break;
}
//------下面组装实体------
if(columnIndex==0){
//设置第一列数据
}
if(columnIndex==1){
//设置第二列数据
}
//以此类推,可根据实际情况自行发挥
hasValue = true;
}
//实体对象扔到集合中
if (hasValue) {
result.add(T);
}
}
}
in.close();
//判断集合中有没有数据,有数据才进行下一步
if(result != null && result.size()>0){
List<T> list = new ArrayList<>();
for (T t : result) {
//这里数据自己看情况操作了
}}}
用到流要try catch,上面只是思路,具体代码根据业务来