上传Excel文件并读取存入数据库

这篇博客介绍了如何在Spring框架下实现Excel文件的上传,并详细解析了在controller层和service实现层的方法,以及在`applicationContext.xml`配置文件中进行的相关设置,以将Excel数据读取并存储到数据库中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

备注:接上篇点击打开链接


1、controller层方法:

<span style="white-space:pre">	</span>@RequestMapping(value = "uploadFile")
	public void uploadFile(Model model, MultipartFile file) throws Exception {
		bluetoothService.uploadFileToDatabase(file);
		model.addAttribute(new Protocol());
	}


2、service实现层方法:


<span style="white-space:pre">	</span>public void uploadFileToDatabase(MultipartFile file) {
		// TODO Auto-generated method stub
		if (file == null) {
			throw new BusinessException(ResponseCode.FAIL.code, "文件为空!");
		}
		String fileName = file.getOriginalFilename();
		if (!(fileName.endsWith(".xls") || fileName.endsWith(".xlsx"))) {
			logger.error("文件{}格式不对,仅支持Excel文件!", fileName);
			throw new BusinessException(ResponseCode.FAIL.code, "文件格式不对,仅支持Excel文件!");
		}
		
		XSSFWorkbook workBook = null;
		try {
			InputStream input = file.getInputStream();
			workBook = new XSSFWorkbook(input);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("===>>文件" + fileName + "异常:" + e.getMessage(), e);
			throw new BusinessException(ResponseCode.FAIL.code, "文件上传异常:" + e.getMessage());
		}
		XSSFSheet sheet = workBook.getSheetAt(0);
		if (sheet != null) {
			int rows = sheet.getPhysicalNumberOfRows();
			for (int i = 1; i < rows; i++) {
				XSSFRow row = sheet.getRow(i);
				for (int j = 0; j < row.getPhysicalNumberOfCells(); j++) {
					XSSFCell cell = row.getCell(j);
					String cellStr = "";
					if (cell != null) {
						cellStr = cell.toString();
					}
					System.out.print("【" + cellStr + "】 ");
				}
				
				System.out.println();
			}
		}
	}


注意:spring配置文件:applicationContext.xml增加配置


<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
         <!-- 指定所上传文件的总大小不能超过800KB......注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 -->
        <property name="maxUploadSize" value="80000000"/>
    </bean>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值