struts2--实现Excel上传并解析

package com.bjpn.actions;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts2.ServletActionContext;

/**
 * 用户上传excel文件到服务端, 解析excel文件
 * 
 * @author zhaoj
 * 
 */
public class ParseExcelAction {

	private File excel;// 必须与表单中的name属性一致
	private String excelFileName;// 必须是name属性+FileName

	public File getExcel() {
		return excel;
	}

	public void setExcel(File excel) {
		this.excel = excel;
	}

	public String getExcelFileName() {
		return excelFileName;
	}

	public void setExcelFileName(String excelFileName) {
		this.excelFileName = excelFileName;
	}

	public String execute() throws IOException {

		// 将客户端的文件上传到服务端
		String desPath = ServletActionContext.getServletContext().getRealPath(
				"/imags");
		File destFile = new File(desPath, excelFileName);
		FileUtils.copyFile(excel, destFile);

		// 解析excel
		// 得到一个excel文件
		HSSFWorkbook book = new HSSFWorkbook(new FileInputStream(destFile));
		// 得到第一张表
		HSSFSheet sheet = book.getSheetAt(0);
		// 遍历输出
		for (int i = 0; i <= sheet.getLastRowNum(); i++) {
			// 得到行
			HSSFRow row = sheet.getRow(i);
			for (int j = 0; j < row.getLastCellNum(); j++) {
				// 得到一行中的单元格
				HSSFCell cell = row.getCell(j);
				System.out.print(cell + "\t");
			}
			System.out.println();
		}

		return "success";
	}
}


<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<script type="text/javascript" src="js/jquery-1.11.1.js"></script>
<script type="text/javascript">
	$(function(){
	
		$("#submitBtn").click(function(){
			var fileName = $("#excel").val();
			var suffix = (fileName.substr(fileName.lastIndexOf("."))).toUpperCase();
			
			//验证文件后缀名
			if(".XLS" != suffix && ".XLSL" == suffix){
				alert("文件格式只能是.XLS或者.XLSL");
				return;
			}
			
			$("#myForm").submit();
		
		});
	
	
	
	});
</script>

</head>

<body>
	<form id="myForm" action="system/parseExcel.do" method="post" enctype="multipart/form-data">
		<input type="file" name="excel" id="excel"/> <br/>
		<input id="submitBtn" type="button" value="提交" />
	</form>

</body>
</html>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值