Excel批量上传前后端实现

如何上传批量数据表格

需要注意的事项:

  • 必须同步提交form表单
  • Form表单编码方式:multipart/form-data
  • 提交的方式必须为post
  • 上传文件对应,type="file",元素要提供name

一键上传原理

一键上传原理图

使用jquery ocupload实现一键上传

导入jquery.ocupload-1.1.2.js到项目中,可自行到官网下载相应版本即可
在页面中引入ocupload.js文件

查看官网的属性和使用方法如下:

$(element).upload( /** options */ ); 

As a stand-alone jQuery function 

$.ocupload($(element), /** options */ ); 

Options 
Both of the functions accept an optional options object, which can contain any or all of the following (default value): 

    * name: ("file") The name of the file input form element. 
    * enctype: ("multipart/form-data") The enctype attribute of the form, it is usually a good idea to leave this as default. 
    * action: (null) The form action attribute, the page that will do the processing on the server side. 
    * autoSubmit: (true) If true the form will be submitted after the user selects a file (after the file browser closes). 
    * params: ({}) Additional paramaters to be sent with the file, creates a hidden form element using the key as the name of the form and the value as the value. 
    * onSubmit: (null) The callback function called before submitting the form. 
    * onComplete: (null) The callback function called after the action page loads. 
    * onSelect: (null) The callback function called after the user has selected a file. 

在jquery easyUI的页面中添加一键导入的按钮,点击按钮完成一键上传效果

限定只能上传指定格式的文件

思路:在选择文件后,关闭自动提交,判定文件格式,再手动提交

//点击导入按钮完成文件上传
				$("#button-import").upload({
					//默认name为file
					action: "../../area_batchImport.action",
					onSelect: function(){
								//选中文件后 关闭自动提交的功能
								this.autoSubmit = false;
								//;判断文件格式是否是以.xls 或者 .xlsx结尾
								var fileName = this.filename();
								var regex= /^.*\.(xls|xlsx)$/;
								if(regex.test(fileName)){
									//匹配就提交表单
									this.submit();
								}else{
									$.messager.alert("警告","只能选择.xls或者.xlsx后缀的文件","warning");
								}
							},
					onComplete: function(response){
						$.messager.alert("提示","文件上传成功","info");
					}
				});

action是必填项,其他可选。onSelect是选择文件的操作。一键上传默认是自动上传的,一般要判断上传的文件类型,所以选择文件的时候先把自动上传设置为false。 onComplete: function(response)是文件上传完毕,服务器响应后的操作。可根据response来判断上传是否成功。

编写服务器代码实现批量导入

使用struts2文件上传机制,接受上传文件

struts2文件上传的原理是在struts-default.xml文件中配置了fileUpload的拦截器。拦截器已经被配置在defaultStack中。 编写action接收上传文件: 在action中定义三个成员变量:

private File [页面元素 name]; private String [页面元素 name]ContentType; private String [页面元素 name]FileName;

其中private File fileName 这个成员变量是必须的,而且fileName要和你上传的文件的input 的name属性值要对应

实现excel文件解析 :POI

POI官网:http://poi.apache.org 支持解析的文档:

输入图片说明

HSSF 解析 Excel 97-2007 格式 (.xls) XSSF 解析 Excel 2007 以上的格式 (.xlsx )

基于maven坐标,导入POI的支持

poi...jar解析HSSF poi ooxml ....jar 解析XSSF (依赖poi包) 在pom.xml文件中配置:

<!-- Excel解析工具类  -->
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi</artifactId>
			<version>${poi.version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-ooxml</artifactId>
			<version>${poi.version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-ooxml-schemas</artifactId>
			<version>${poi.version}</version>
		</dependency>

解析Excel逻辑: 工作簿 ---sheet ---row ---cell

Action代码
//注入service层对象
	@Autowired
	private AreaService areaService;
    //接收文件上传
	private File file;
	
	public void setFile(File file) {
		this.file = file;
	}

// 接收文件上传
	private File file;
	private String fileFileName;

	public void setFile(File file) {
		this.file = file;
	}

	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}

	// xls,xlsx文件上传完成区域批量导入

	@Action(value = "area_batchImport")
	public String batchImport() throws IOException {
		List<Area> areaList = new ArrayList<Area>();
		Workbook workbook = null;

		if (fileFileName.endsWith(".xls")) {
			workbook = new HSSFWorkbook(new FileInputStream(file));
		} else if (fileFileName.endsWith(".xlsx")) {
			workbook = new XSSFWorkbook(new FileInputStream(file));
		}
		// 编写解析.xls代码逻辑
		// 1.加载excel文件对象
		// 2.读取一个sheet
		Sheet sheet = workbook.getSheetAt(0);
		// 3.读取sheet中的每一行
		for (Row row : sheet) {
			// 一行数据对应一个对象
			if (row.getRowNum() == 0) {
				// 第一行表头要跳过
				continue;
			}
			// 跳过空行
			if (row.getCell(0) == null || StringUtils.isBlank(row.getCell(0).getStringCellValue())) {
				continue;
			}

			Area area = new Area();
			area.setId(row.getCell(0).getStringCellValue());
			area.setProvince(row.getCell(1).getStringCellValue());
			area.setCity(row.getCell(2).getStringCellValue());
			area.setDistrict(row.getCell(3).getStringCellValue());
			area.setPostcode(row.getCell(4).getStringCellValue());

			areaList.add(area);
		}
		// 调用service层
		areaService.saveBatch(areaList);

		return NONE;
	}
Service层
@Service
@Transactional
public class AreaServiceImpl implements AreaService {
	@Autowired
	private AreaRepository areaRepository;

	@Override
	public void saveBatch(List<Area> areaList) {
		areaRepository.save(areaList);
	}
}
DAO层

public interface AreaRepository extends JpaRepository<Area, String>,
		JpaSpecificationExecutor<Area>{
    //这里不需要写代码
}

转载于:https://my.oschina.net/wuzhentao/blog/1333620

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值