最近公司要做excel导入,之前从来没有做过,在网上查阅了一些资料,总结一下,以防后面要用可以找到
前端页面:
<span
style="display: inline-block; width: 100px; text-align: right;">选择文件:
</span> <input id = "excel" name = "file" class="easyui-filebox" style="width:175px" data-options="buttonText:'选择文件', prompt:'请选择文件...'">
js 代码:
<script type="text/javascript">
$("#uploadExcels").form({
type : 'post',
url : '',
dataType : "json",
onSubmit: function() {
var fileName= $('#excel').filebox('getValue');
//对文件格式进行校验
var d1=/\.[^\.]+$/.exec(fileName);
console.log(d1)
var userType=$("#userType").val();
if (fileName == "") {
$.messager.alert('Excel批量用户导入', '请选择将要上传的文件!');
return false;
}else if(d1!=".xlsx"&&d1!=".xls"){
$.messager.alert('提示','请选择正确的Excle文件格式!','info');
return false;
}
//按钮置灰,只允许点击一次
$("#booten").linkbutton('disable');
return true;
},
success : function(result) {
。。。。。。
}
});
</script>
后端代码:
controller层:
// 上传excel文件
@RequestMapping("/uploude")
@ResponseBody
public BaseRemark uploudexcelquestion(MultipartFile file, HttpServletRequest req){
String path = req.getSession().getServletContext().getRealPath("upload");
File file1 = new File(path);
try {
// 创建一个文件解析工具类
ReadExcelTest readExcelTest = new ReadExcelTest();
//解析前面传过来的文件
List<Map<String, String>> list = readExcelTest.getExcelInfo(file);
for (Map<String, String> map : list) {
DrugSocialQuestion question = new DrugSocialQuestion();
question.setTitle(map.get("title"));
question.setType(Integer.valueOf(map.get("type")));
question.setQuestionType(Integer.valueOf(map.get("questionType")));
drugSocialQuestionMapper.insertSelective(question);
}
return new BaseRemark();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
BaseRemark<Object> ba = new BaseRemark<>();
ba.setRemark(BaseRemark.FAILE);
ba.setCode(BaseRemark.RAND_CODE);
return ba;
}
}
//创建上传工具类
public class ReadExcelTest {
// 总行数
private int totalRows = 0;
// 总列数
private int totalCells = 0;
// 错误信息接收器
private String errorMsg;
// 构造方法
public ReadExcelTest() {
}
//获取总条数
public int getTotalRows() {
return totalRows;
}
public void setTotalRows(int totalRows) {
this.totalRows = totalRows;
}
//获取总列数
public int getTotalCells() {
return totalCells;
}
public void setTotalCells(int totalCells) {
this.totalCells = totalCells;
}
//获取错误接收器
public String getErrorMsg() {
return errorMsg;
}
public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
}
/**
* 读EXCEL文件,获取信息集合
*
* @param fielName
* @return
* 1、先验证文件的格式是否正确(固定格式,拷贝就可以用的) 2、在格式正确的前提下判断文件的版本 3、最后根据版本获取文件里面的内容
*/
public List<Map<String, String>> getExcelInfo(MultipartFile mFile) {
String fileName = mFile.getOriginalFilename();// 获取文件名
try {
if (!validateExcel(fileName)) {// 第一步:验证文件名是否合格
return null;
}
boolean isExcel2003 = true;
if (isExcel2007(fileName)) { // 第二步:根据文件名判断文件是2003版本还是2007版本,当isExcel2003为true时,为2003版本,当isExcel2003为false时,为2007版本
isExcel2003 = false;
}
return createExcel(mFile.getInputStream(), isExcel2003);//第三步:根据版本获取文件中的内容
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 157 * 验证EXCEL文件
* 158 *
* 159 * @param filePath
* 160 * @return
* 161
*/
public boolean validateExcel(String filePath) {
if (filePath == null || !(isExcel2003(filePath) || isExcel2007(filePath))) {
errorMsg = "文件名不是excel格式";
return false;
}
return true;
}
// @描述:是否是2003的excel,返回true是2003
public static boolean isExcel2003(String filePath) {
return filePath.matches("^.+\\.(?i)(xls)$");
}
// @描述:是否是2007的excel,返回true是2007
public static boolean isExcel2007(String filePath) {
return filePath.matches("^.+\\.(?i)(xlsx)$");
}
/**
* 根据excel里面的内容读取客户信息
*
* @param is 输入流
* @param isExcel2003 excel是2003还是2007版本
* @return
* @throws IOException
*/
public List<Map<String,String>> createExcel(InputStream is, boolean isExcel2003) {
try {
Workbook wb = null;
if (isExcel2003) {// 当excel是2003时,创建excel2003
wb = new HSSFWorkbook(is);
} else {// 当excel是2007时,创建excel2007
wb = new XSSFWorkbook(is);
}
return readExcelValue(wb);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private List<Map<String, String>> readExcelValue2(Workbook wb) {
// 得到第一个shell
Sheet sheet = wb.getSheetAt(0);
// 得到Excel的行数
this.totalRows = sheet.getPhysicalNumberOfRows();
// 得到Excel的列数(前提是有行数)
if (totalRows > 1 && sheet.getRow(0) != null) {
this.totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
}
List<Map<String, String>> userList = new ArrayList<Map<String, String>>();
// 循环Excel行数
for (int r = 1; r < totalRows; r++) {
Row row = sheet.getRow(r);
if (row == null) {
continue;
}
// 循环Excel的列
Map<String, String> map = new HashMap<String, String>();
for (int c = 0; c < this.totalCells; c++) {
Cell cell = row.getCell(c);
if (null != cell) {
if (c == 0) {
cell.setCellType(Cell.CELL_TYPE_STRING);
if(cell.getStringCellValue()==null||cell.getStringCellValue().equals("")){
break;
}
map.put("idCard", cell.getStringCellValue());
} else if (c == 1) {
//姓名
cell.setCellType(Cell.CELL_TYPE_STRING);
map.put("score", cell.getStringCellValue());
}
}
}
userList.add(map);
}
return userList;
}
}