SpringBoot中导入Excel的总结

1 先导入配置文件

        <dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi</artifactId>
		</dependency>
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-ooxml</artifactId>
		</dependency>
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-ooxml-schemas</artifactId>
		</dependency>

2 编写Chontroller

/**
     * 上传excel文件 
     * @author SHF
     * @version 创建时间:2018年12月14日  上午9:28:14
     *  @param excelInput  
     *  @param type  1:大客户经理 2内部人员'
     *  @return
     * @throws Exception 
     */
    @RequestMapping("/uploadExcel")
    @ResponseBody
    public Object uploadExcel(@RequestParam("excelInput") MultipartFile excelInput,Integer type) throws Exception{
    	// 检查文件类型
		String fileName = checkFile(excelInput);
		if("1".equals(fileName) || "2".equals(fileName)) {
			return new SuccessTip("请上传Excel格式的文件");
		}
		Workbook workbook = null;
		InputStream inputStream = excelInput.getInputStream();
		List<String[]> list = new ArrayList<String[]>();
		
		try {
			workbook = WorkbookFactory.create(inputStream);
			int numberOfSheets = workbook.getNumberOfSheets();
			if (numberOfSheets > 0) {
				Sheet sheet = workbook.getSheetAt(0);
				if (null != sheet) {
					// 获得当前sheet的开始行
					int firstRowNum = sheet.getFirstRowNum();
					// 获得当前sheet的结束行
					int lastRowNum = sheet.getLastRowNum();

					for (int rowNum = firstRowNum; rowNum <= lastRowNum; rowNum++) {
						// 获得当前行
						Row row = sheet.getRow(rowNum);
						if (row == null) {
							continue;
						}
						// 获得当前行的开始列
						int firstCellNum = row.getFirstCellNum();
						// 获得当前行的列数
						int lastCellNum = row.getLastCellNum();
						if(lastCellNum != 3) {
							//必须要有三列数据
							return new SuccessTip("上传的数据不能有为空值!");
						}
						String[] cells = new String[row.getLastCellNum()];
						// 循环当前行
						for (int cellNum = firstCellNum; cellNum < lastCellNum; cellNum++) {
							Cell cell = row.getCell(cellNum);
							cells[cellNum] = getCellValue(cell);
						}
						list.add(cells);
					}
				}
			}
			
			//插入数据
			if (!list.isEmpty()) {
				for (String[] strs : list) {
					Integer userId = ShiroKit.getUser().getId();
			    	Date date = new Date();
					String name = strs[0];
					String dept_userType = strs[1];
					String phone = strs[2];
					
					/*if(StringUtils.isBlank(phone)) {
						//throw new Exception("手机号码不能为空");
						return new SuccessTip("手机号码不能为空");
					}*/
					ProjectInnerUser tProjectInnerUser = tProjectInnerUserService.selectOne(new EntityWrapper<ProjectInnerUser>().eq("phone", phone).eq("is_enable", 1).eq("is_deleted", 0));
					if(tProjectInnerUser == null) {
						tProjectInnerUser = new ProjectInnerUser();
						tProjectInnerUser.setName(name);
						tProjectInnerUser.setPhone(phone);
						if(type == 1) {
							tProjectInnerUser.setDept(dept_userType);
						}else {
							tProjectInnerUser.setUserType(dept_userType);
						}
						tProjectInnerUser.setType(type);
						tProjectInnerUser.setRemark("excel导入的数据");
						tProjectInnerUser.setIsDeleted(0);
						tProjectInnerUser.setIsEnable(1);
						tProjectInnerUser.setCreator(userId);
						tProjectInnerUser.setCreated(new Date());
						tProjectInnerUser.setModifier(userId);
						tProjectInnerUser.setModified(date);
						tProjectInnerUserService.insert(tProjectInnerUser);
					}else {
						tProjectInnerUser.setName(name);
						if(type == 1) {
							tProjectInnerUser.setDept(dept_userType);
						}else {
							tProjectInnerUser.setUserType(dept_userType);
						}
						tProjectInnerUser.setType(type);
						tProjectInnerUser.setRemark("excel导入的数据");
						tProjectInnerUser.setModifier(userId);
						tProjectInnerUser.setModified(date);
						tProjectInnerUserService.updateById(tProjectInnerUser);
					}
					
					
				}
			}
			
			
		} catch (EncryptedDocumentException e1) {
			e1.printStackTrace();
		} catch (InvalidFormatException e1) {
			e1.printStackTrace();
		} finally {
			if (null != workbook) {
				workbook.close();
			}
			if (null != inputStream) {
				inputStream.close();
			}
		}
		
    	return SUCCESS_TIP;
    }
    
    public static String checkFile(MultipartFile file) throws IOException {
		// 判断文件是否存在
		if (null == file) {
			//throw new GunsException(BizExceptionEnum.FILE_NOT_FOUND);
			return "1";//文件不存在
		}
		// 获得文件名
		String fileName = file.getOriginalFilename();
		// 判断文件是否是excel文件
		if (!fileName.endsWith("xls") && !fileName.endsWith("xlsx")) {
			//throw new GunsException(BizExceptionEnum.UPLOAD_NOT_EXCEL_ERROR);
			return "2";//上传的不是excel文件
		}
		return fileName;
	}
    
    /**
	 * 根据不同类型获取值
	 * 
	 * @param cell
	 * @return
	 */
	public static String getCellValue(Cell cell) {
		String cellValue = "";
		if (cell == null) {
			return cellValue;
		}
		// 判断数据的类型
		switch (cell.getCellTypeEnum()) {
		case NUMERIC: // 数字
			cellValue = stringDateProcess(cell);
			break;
		case STRING: // 字符串
			cellValue = String.valueOf(cell.getStringCellValue());
			break;
		case BOOLEAN: // Boolean
			cellValue = String.valueOf(cell.getBooleanCellValue());
			break;
		case FORMULA: // 公式
			cellValue = String.valueOf(cell.getCellFormula());
			break;
		case BLANK: // 空值
			cellValue = "";
			break;
		case ERROR: // 故障
			cellValue = "非法字符";
			break;
		default:
			cellValue = "未知类型";
			break;
		}
		return cellValue;
	}
	
	/**
	 * 时间格式转换
	 * 
	 * @param cell
	 * @return
	 */
	public static String stringDateProcess(Cell cell) {
		String result = new String();
		if (HSSFDateUtil.isCellDateFormatted(cell)) {// 处理日期格式、时间格式
			SimpleDateFormat sdf = null;
			if (cell.getCellStyle().getDataFormat() == HSSFDataFormat.getBuiltinFormat("h:mm")) {
				sdf = new SimpleDateFormat("HH:mm ");
			} else {// 日期
				sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
			}
			Date date = cell.getDateCellValue();
			result = sdf.format(date);
		} else if (cell.getCellStyle().getDataFormat() == 58) {
			// 处理自定义日期格式:m月d日(通过判断单元格的格式id解决,id的值是58)
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
			double value = cell.getNumericCellValue();
			Date date = org.apache.poi.ss.usermodel.DateUtil.getJavaDate(value);
			result = sdf.format(date);
		} else {
			double value = cell.getNumericCellValue();
			CellStyle style = cell.getCellStyle();
			DecimalFormat format = new DecimalFormat();
			String temp = style.getDataFormatString();
			// 单元格设置成常规
			if (temp.equals("General")) {
				format.applyPattern("#");
			}
			result = format.format(value);
		}

		return result;
	}

 

3 页面我们使用Jquery的form表单上传 jquery.form.js  地址:https://github.com/jquery-form/form

@layout("/common/_container.html"){
<script src="${ctxPath}/static/js/jquery.form.js"></script>
<div class="ibox float-e-margins">
    <div class="ibox-content">
        <div class="form-horizontal">
        	<form id="form1" method="post" enctype="multipart/form-data">
	        	<input type="hidden" value="${type!}" id="type" name="type" accept="xlsx">
	        	<input type="file" class="form-control" name="excelInput" id="excelInput" >
	        	<p>长传文件的格式:</p>
	        	<div style="font-size:16px;">
				  <p style="float:left;width:100px;">姓名</p>
				  <p style="float:left;width:100px;">部门</p>
				  <p style="float:left;width:100px;">手机号码 </p>
				</div>
	            <div class="row">
	                <div class="flexca">
	                	<input type="reset" class="btn btn-warning" onClick="closePag()" value="取消">
	                	<input type="submit" id="tj" class="btn btn-primary" value="提交" style="margin-left:65px;">
	                </div>
	            </div>
        	</form>
        </div>
    </div>
</div>
<script type="text/javascript">
	var type = null;
	
	$(function(){
		 type = $("#type").val();//全局配置文件的类型 1:表示从大客户经理页面跳转过来的  2:表示从内部员工页面跳转过来的
		/** 验证文件是否导入成功  */
		var options = {
		    target:'#form1',
		    url:Feng.ctxPath + "/bigUser/uploadExcel",
		    success:function(data) {
		        if(data.code == 200){
		        	Feng.success("上传成功!");
		        }else{
		        	Feng.error("上传失败!"+data.message);
		        }
		    	closePag();
		    }
		};
		$('#form1').ajaxForm(options);     
	});
	//关闭弹框
	function closePag(){
		if(type == 1){
			parent.layer.close(window.parent.TBigUser.layerIndex);
			window.parent.TBigUser.table.refresh();
		}else{
			parent.layer.close(window.parent.InsideUser.layerIndex);
			window.parent.InsideUser.table.refresh();
		}
	}
//-->
</script>
@}

或者使用ajax的方式提交表单(这样可以减少兼容性)

$(function(){
		 type = $("#type").val();//全局配置文件的类型 1:表示从大客户经理页面跳转过来的  2:表示从内部员工页面跳转过来的
		 $("#tj").click(function () {
	            var formData = new FormData($('#form1')[0]);
	            $.ajax({
	                type: 'post',
	                url: Feng.ctxPath + "/bigUser/uploadExcel",
	                data: formData,
	                cache: false,
	                processData: false,
	                contentType: false,
	            }).success(function (data) {
	            	if(data.code == 200){
	 		        	Feng.success("上传成功!");
	 		        }else{
	 		        	Feng.error("上传失败!"+data.message);
	 		        }
	 		    	closePag();
	            }).error(function () {
	                alert("上传失败");
	            });
	        }); 
		  
	});

 

 

转载于:https://my.oschina.net/u/3677987/blog/2988429

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Spring Boot可以使用POI库来导入Excel文件。POI是一个Java库,用于读取和写入Microsoft Office格式的文件,包括Excel。以下是使用Spring Boot和POI导入Excel文件的基本步骤: 1. 添加POI依赖 在pom.xml文件添加以下依赖: ``` <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.1.2</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.2</version> </dependency> ``` 2. 创建Excel文件 在Excel创建一个表格,包含要导入的数据。确保表格的列名与Java的属性名称相匹配。 3. 创建Java类 创建一个Java类来表示Excel的数据。该类应该包含与Excel表格的列相对应的属性。 4. 创建Controller 创建一个Spring Boot控制器,用于处理Excel文件的导入。在控制器,使用POI库来读取Excel文件,并将数据映射到Java对象。 5. 测试导入 使用Postman或其他HTTP客户端测试导入功能。将Excel文件作为请求体发送到控制器,并验证数据是否已成功导入。 以上是使用Spring Boot和POI导入Excel文件的基本步骤。 ### 回答2: Spring Boot 是一个快速开发框架,它通过自动配置帮助开发人员快速搭建应用程序,POI 则是一款提供操作 Microsoft Office 文件的 Java 库。在开发过程,经常需要将数据导入 Excel 表格,使用 Spring Boot 和 POI 结合起来,可以更加简单地实现数据导入 Excel 的功能。 首先,需要在 Maven 引入 POI 相关依赖: ``` <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.1.2</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.2</version> </dependency> ``` 接下来,使用 Spring Boot 提供的文件上传组件 MultipartFile 接收上传的文件,并使用 POI 的工具类读取 Excel 文件的数据: ``` import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import java.io.InputStream; @RestController public class ExcelController { @PostMapping("/import") public String importExcel(@RequestParam("file") MultipartFile file) throws Exception { InputStream inputStream = file.getInputStream(); XSSFWorkbook workbook = new XSSFWorkbook(inputStream); // 获取第一个工作表 XSSFSheet sheet = workbook.getSheetAt(0); for (Row row : sheet) { for (Cell cell : row) { String value = cell.getStringCellValue(); System.out.println(value); } } workbook.close(); inputStream.close(); return "success"; } } ``` 在上述代码,首先通过 MultipartFile 对象获取上传的文件,然后获取文件的输入流并传给 XSSFWorkbook 类,通过该类的 getSheetAt() 方法获取第一个工作表,接着循环遍历每一行和每一列的单元格,使用 getStringCellValue() 方法获取每个单元格的值。 值得注意的是,上述代码只是简单地读取 Excel 文件的数据,如果需要将数据插入或更新至数据库,还需要对读取到的数据进行处理。 综上所述,使用 Spring Boot 和 POI 结合实现数据导入 Excel 的功能,既方便又高效,能够提高开发效率,并且可以通过扩展代码实现更多的功能。 ### 回答3: Spring Boot是一个基于Spring框架的快速开发应用程序的工具。它很适合于开发Web应用程序和微服务。在Spring Boot项目使用POI(Poor Obfuscation Implementation)导入Excel文件可以方便地读取和处理大量数据。以下是关于如何使用Spring Boot和POI导入Excel的详细步骤。 第一步:在pom.xml导入POI库依赖 ```xml <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.0.1</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.0.1</version> </dependency> ``` 第二步:编写处理Excel文件的Java程序 1. 首先使用@RequestMapped注释将处理程序的URL映射到控制器类。 ```java @Controller @RequestMapping("/excel") public class ExcelController { } ``` 2. 通过使用@RequestParam注释接收上传Excel文件的请求,并使用MultipartFile对象处理上传的Excel文件。 ```java @PostMapping("/upload") public String upload(@RequestParam("file") MultipartFile file) { } ``` 3. 读取Excel数据需要使用POI的对象,首先我们需要定义一个Workbook对象来表示整个Excel文件。 ```java Workbook workbook = null; ``` 4. 接下来使用try/catch块加载Excel文件,并使用XSSFWorkbook对象将文件数据转换成Workbook对象。 ```java try { workbook = new XSSFWorkbook(file.getInputStream()); } catch (IOException e) { e.printStackTrace(); } ``` 5. 通过Workbook对象获取Sheet对象,Sheet对象表示Excel文件的一个工作表。 ```java Sheet sheet = workbook.getSheetAt(0); ``` 6. 接下来,使用for循环遍历工作表的每一行。 ```java for (Row row: sheet) { } ``` 7. 在for循环,我们可以使用getCell()方法获取每一行的单元格数据。 ```java Cell cell = row.getCell(0); ``` 8. 使用if语句检查单元格数据类型。 ```java if (cell.getCellType() == CellType.STRING) { } ``` 9. 如果单元格数据是字符串,则使用getString()方法获取该单元格的值。 ```java String cellValue = cell.getStringCellValue(); ``` 10. 最后,关闭workbook对象并返回结果。 ```java workbook.close(); return "redirect:/success"; ``` 总结:通过Spring Boot框架和POI库,处理Excel文件已经变得很简单。我们只需要在配置文件导入POI库依赖项,编写处理Excel文件的Java程序,然后在控制器类将其映射到相应的URL路径即可。通过这种方法,我们可以快速地读取和处理大量的Excel数据。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值