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>