- 导入Excel工具类
package com.baidu.gongyi.auction.util;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/**
* 导入Excel
*
*
*/
public class UploadExcelUtil {
private static final String excel2003L = ".xls"; // 2003- 版本的excel
private static final String excel2007U = ".xlsx"; // 2007+ 版本的excel
/**
* 描述:获取IO流中的数据,组装成List<List<Object>>对象
*
* @param in,fileName
* @return
* @throws IOException
*/
public List<List<Object>> getListByExcel(InputStream in, String fileName) throws Exception {
List<List<Object>> list = null;
// 创建Excel工作薄
Workbook work = this.getWorkbook(in, fileName);
if (null == work) {
throw new Exception("创建Excel工作薄为空!");
}
Sheet sheet = null;
Row row = null;
Cell cell = null;
list = new ArrayList<List<Object>>();
// 遍历Excel中所有的sheet
for (int i = 0; i < work.getNumberOfSheets(); i++) {
sheet = work.getSheetAt(i);
if (sheet == null) {
continue;
}
// 遍历当前sheet中的所有行
for (int j = 1; j <= sheet.getLastRowNum(); j++) {
int physicalNumberOfCells = sheet.getRow(0).getPhysicalNumberOfCells();
row = sheet.getRow(j);
if (row == null) {
row = sheet.createRow(j);
cell = row.createCell(physicalNumberOfCells);
}
// 遍历所有的列
List<Object> li = new ArrayList<Object>();
for (int y = 0; y < physicalNumberOfCells; y++) {
cell = row.getCell(y);
if (cell == null) {
li.add("");
continue;
}
li.add(this.getCellValue(cell));
}
list.add(li);
}
}
work.close();
return list;
}
/**
* 描述:根据文件后缀,自适应上传文件的版本
*
* @param inStr,fileName
* @return
* @throws Exception
*/
public Workbook getWorkbook(InputStream inStr, String fileName) throws Exception {
Workbook wb = null;
String fileType = fileName.substring(fileName.lastIndexOf("."));
if (excel2003L.equals(fileType)) {
wb = new HSSFWorkbook(inStr); // 2003-
} else if (excel2007U.equals(fileType)) {
wb = new XSSFWorkbook(inStr); // 2007+
} else {
throw new Exception("解析的文件格式有误!");
}
return wb;
}
/**
* 描述:对表格中数值进行格式化
*
* @param cell
* @return
*/
@SuppressWarnings("deprecation")
public Object getCellValue(Cell cell) {
Object value = null;
DecimalFormat df = new DecimalFormat("0"); // 格式化number String字符
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // 日期格式化
DecimalFormat df2 = new DecimalFormat("0.00"); // 格式化数字
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
value = cell.getRichStringCellValue().getString();
break;
case Cell.CELL_TYPE_NUMERIC:
if ("General".equals(cell.getCellStyle().getDataFormatString())) {
value = df.format(cell.getNumericCellValue());
} else if ("m/d/yy".equals(cell.getCellStyle().getDataFormatString())) {
value = sdf.format(cell.getDateCellValue());
} else {
value = df2.format(cell.getNumericCellValue());
}
break;
case Cell.CELL_TYPE_BOOLEAN:
value = cell.getBooleanCellValue();
break;
case Cell.CELL_TYPE_BLANK:
value = "";
break;
default:
break;
}
return value;
}
}
- Controller
@Controller
public class MConvocatorController extends BaseController {
@Autowired
private MConvocatorService mConvocatorService;
/**
* 描述:通过传统方式form表单提交方式导入excel文件
*
* @param request
* @throws Exception
*/
@RequestMapping(value = "/convocator/upload", method = { RequestMethod.GET, RequestMethod.POST })
public void uploadExcel(HttpServletRequest request, Writer writer) throws Exception {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
System.out.println("通过传统方式form表单提交方式导入excel文件!");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
InputStream in = null;
List<List<Object>> convocatorList = null;
MultipartFile file = multipartRequest.getFile("upfile");
if (file.isEmpty()) {
throw new Exception("文件不存在!");
}
in = file.getInputStream();
convocatorList = new UploadExcelUtil().getListByExcel(in, file.getOriginalFilename());
in.close();
String mapStr = "";
MConvocator mConvocator = null;
List<Object> lo = null;
try {
// 调用service相应方法进行数据保存到数据库中
for (int i = 0; i < convocatorList.size(); i++) {
lo = convocatorList.get(i);
mConvocator = new MConvocator();
mConvocator.setName(String.valueOf(lo.get(0)));
mConvocator.setMobile(String.valueOf(lo.get(1)));
mConvocator.setEmail(String.valueOf(lo.get(2)));
mConvocator.setCompanyName(String.valueOf(lo.get(3)));
mConvocator.setCreateTime(sdf.parse((String.valueOf(lo.get(4)))));
if ("未签到".equals(String.valueOf(lo.get(5)))) {
mConvocator.setStatus(0);
} else if ("已签到门票核销".equals(String.valueOf(lo.get(5)))) {
mConvocator.setStatus(1);
} else {
mConvocator.setStatus(2);
}
mConvocator.setSignTime(sdf.parse((String.valueOf(lo.get(6)))));
mConvocatorService.insertMConvocatorByExcel(mConvocator);
}
mapStr = MessageBeanUtils.buildDataMessage2(null, true, "操作成功");
} catch (Exception e) {
mapStr = MessageBeanUtils.buildDataMessage2(Collections.emptyList(), false, "操作失败");
LoggerHelper.err(getClass(), e.getMessage(), e);
}
writer.write(mapStr);
}
}
service
/**
* 导入操作,批量保存参会人
* @param mConvocator
* @return
*/
@Transactional
public int insertMConvocatorByExcel(MConvocator mConvocator){
mConvocator.setUpdateTime(new Date());
Long orgId = ** .getOrgId();
if (orgId != null) {
mConvocator.setOrgId(orgId);
}
return mConvocatorDao.insertSelective(mConvocator);
}
- main.vm
<link rel="stylesheet" type="text/css" href="${context.contextPath}/css/common.css?v=1">
<link rel="stylesheet" type="text/css" href="${context.contextPath}/css/activity.css?v=1">
<script src="${context.contextPath}/lib/dist/My97DatePicker/WdatePicker.js?v=1"></script>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<base href="<%=basePath%>">
</head>
<body>
<div>1.通过简单的form表单提交方式,进行文件的上2.通过jquery.form.js插件提供的form表单一步提交功能 </div>
<form method="POST" enctype="multipart/form-data" id="form1" action="$!{context.contextPath}/convocator/upload">
<table>
<tr>
<td>上传文件: </td>
<td> <input id="upfile" type="file" name="upfile"></td>
</tr>
<tr>
<td><input type="submit" value="提交" onclick="return checkData()"></td>
<td><input type="button" value="ajax方式提交" id="btn" name="btn" ></td>
</tr>
</table>
</form>
</body>
</body>
</html>