当向系统中导入数据时,更多的使用是Excel形式的数据导入。在此给个demo。
1、首先是前端界面:
<form action="upload" enctype="multipart/form-data">
<input type="file" name="myFile" />
<input type="submit" value="Upload! " />
</form>
关于这个只需要注意两点:1)enctype属性的值为multipart/form-data 2) type属性的值为file 而对于上述form表单中的name="myFile",则是因为后台需要name属性值作为参数,获取MultipartFile对象。
2、使用multipart请求处理文件上传:
Spring通过对ServletAPI的HttpServletRequest接口进行扩展,使其能够更好的处理文件上传,扩展后的接口名为:org.springframework.web.multipart.MultipartHttpServletRequest(接口提供的方法有public MultipartFile getFile(String name); public Map getFile(); public Iterator getFileNames();)
实际上只要发现一个就表明在控制器实例中存在一个实现MultipartHttpServletRequest接口的requset对象。
MultipartFile multipartFile = request.getFile("myFile")。如果请求中找不到文件,则返回null。
org.springframework.web.multipart.MultipartFile接口提供的方法有:
public byte[] getBytes();
public String getContentType();//获得文件类型
public java.io.InputStream getInputStream();将文件读取为java.io.InputStream流对象
public String getName();
public String getOriginalFilename();
public long getSize();//获取文件长度
public boolean isEmpty();
public void transferTo(java.io.File dest);//用于将上传文件写到服务器指定的文件。
以下实例代码:将Excel文件转换成流信息
public static InputStream getInputStreamFromSingleFile(
HttpServletRequest request) throws Exception {
MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
MultipartFile multipartFile = multipartHttpServletRequest
.getFile("myFile");
InputStream in = null;
if (multipartFile != null && !multipartFile.isEmpty()) {
String fileName = multipartFile.getOriginalFilename();
if (POIExcelUtil.isValidFileName(fileName.trim())
&& POIExcelUtil.isXlsFileName(fileName.trim())) {
in = multipartFile.getInputStream();
} else {
throw new BusiException("必须是微软Excel格式文件!");
}
} else {
throw new BusiException("请选择导入的文件!");
}
return in;
}
/**
* 判断是否合法的文件名
*
* @param fileName
* @return
*/
public static boolean isValidFileName(String fileName) {
if (fileName == null || fileName.length() > 255
|| !fileName.contains("."))
return false;
else
return fileName
.matches("[^\\s\\\\/:\\*\\?\\\"<>\\|](\\x20|[^\\s\\\\/:\\*\\?\\\"<>\\|])*[^\\s\\\\/:\\*\\?\\\"<>\\|\\.]$");
}
/**
* 判断是否合法的Excel文件
*
* @param fileName
* @return
*/
public static boolean isXlsFileName(String fileName) {
return fileName.matches("^.+\\.(?i)((xls)|(xlsx))$");
}
3、将流信息转换为对象
InputStream inputStream = POIExcelUtil.getInputStreamFromSingleFile(request);
if (inputStream != null) {// 上传文件
HSSFRow row = null;
HSSFWorkbook wb = new HSSFWorkbook(inputStream);
HSSFSheet sheet = wb.getSheetAt(0);
int totalRows = sheet.getLastRowNum();
if (totalRows < 1) {
throw new BusiException("导入数据为空!");
}
if (totalRows > 10000) {
throw new BusiException("导入数据最多为10000条!");
}
List<People> list = new ArrayList<People>();
People people = null;
for (int r = 1; r <= totalRows; r++) {
row = sheet.getRow(r);
// 空行则继续下面
if (POIExcelUtil.isBlankLine(row))
continue;
String name = POIExcelUtil
.getCellStringValue(row.getCell(0)).replaceAll(" ", "").replaceAll(" ", "");
String sex = POIExcelUtil
.getCellStringValue(row.getCell(1)).replaceAll(" ", "").replaceAll(" ", "");
String qq = POIExcelUtil
.getCellStringValue(row.getCell(2)).replaceAll(" ", "").replaceAll(" ", "");
String phone1 = POIExcelUtil
.getCellStringValue(row.getCell(3)).replaceAll(" ", "").replaceAll(" ", "");
String mobile1 = POIExcelUtil
.getCellStringValue(row.getCell(4)).replaceAll(" ", "").replaceAll(" ", "");
String email = POIExcelUtil
.getCellStringValue(row.getCell(5)).replaceAll(" ", "").replaceAll(" ", "");
String depName = POIExcelUtil
.getCellStringValue(row.getCell(6)).replaceAll(" ", "").replaceAll(" ", "");
String posName = POIExcelUtil
.getCellStringValue(row.getCell(7)).replaceAll(" ", "").replaceAll(" ", "");
if (name != null && !name.equalsIgnoreCase("")
&& sex != null && !sex.equalsIgnoreCase("")) {
people = new People(name, "1",
sex.equalsIgnoreCase("男") ? true : false, qq,
phone1, mobile1, email, depName, posName);
people .setId(UUID.randomUUID().toString());
list.add(people );
}
}
/**
* 判断是否空行
*
* @param row
* @return
*/
public static boolean isBlankLine(HSSFRow row) {
if (row == null)
return true;
boolean isBlankLine = true;
for (int j = 0; j < row.getLastCellNum(); j++) {
if (row.getCell(j) != null
&& !"".equals(row.getCell(j).getRichStringCellValue())) {
isBlankLine = false;
break;
}
}
return isBlankLine;
}
4、将数据集合保存才数据库中即可。