设为首页 收藏本站
查看: 456|回复: 0

[经验分享] apache poi 读取Excel文件内容(2003,2007)

[复制链接]

尚未签到

发表于 2017-1-9 09:32:30 | 显示全部楼层 |阅读模式
  很久没记录了,前一段做了个只读取Excel文件内容的需求,今天整理出来,备份一下。
  项目名称 Test
  直接上代码
  index.jsp

<%@ 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>
<title>读取的Excel文件内容(2003,2007)</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">   
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!-- 引入jQuery -->
<script type="text/javascript" src="/js/jquery.js"></script>
<script type="text/javascript">
//提交Excel
function importExcel(){
var fileExcel = $("#fileExcel").val();
// 导入文件必选项
if(fileExcel==""||fileExcel==null){
alert("请选择要导入Excel文件!");
return false;
}
// 判断文件类型
if(fileExcel!=""&&fileExcel!=null){
var hz = fileExcel.substr(fileExcel.lastIndexOf(".")+1);
if(hz!="xls"&&hz!="xlsx"){
alert("请按提示导入指定类型文件!");
return false;
}
}
//获得客户端上传的实际路径
$("#filePath").val(fileExcel);
return true;
}
</script>
</head>
<body>
<form action="<%=request.getContextPath()%>/Excel.do?method=read" id="excelForm" name="excelForm" method="post" enctype="multipart/form-data" >
<table align="center" border="0">
<tr>
<td>
请选择读取的Excel文件:
<input type="file" id="fileExcel" name="file" title="请选择文件">&nbsp;&nbsp;&nbsp;
<font style="color: red;">注:.xls或.xlsx</font></br>
<input type="hidden" id="filePath" name="filePath" value="">
<input type="submit" value="提 交" title="提 交">
<input type="reset" value="重 置" title="重 置">
</td>
</tr>
</table>
</form>
</body>
</html>

  struts-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" "http://struts.apache.org/dtds/struts-config_1_3.dtd">
<struts-config>
<form-beans>
<form-bean name="excelForm" type="com.test.struts.form.ExcelForm"></form-bean>
</form-beans>
<global-exceptions />
<global-forwards />
<action-mappings>
<action path="/Excel" name="excelForm" type="com.test.struts.action.ExcelReadAction" scope="request" parameter="method"></action>
</action-mappings>
<message-resources parameter="com.test.struts.ApplicationResources" />
</struts-config>

  web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.5" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!-- 编码过滤器 -->
<filter>
<filter-name>Set Character Encoding</filter-name>
<filter-class>com.test.struts.filter.SetCharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>ignore</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>Set Character Encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- struts1配置 -->
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<init-param>
<param-name>debug</param-name>
<param-value>3</param-value>
</init-param>
<init-param>
<param-name>detail</param-name>
<param-value>3</param-value>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!-- 常见异常错误处理 -->
<error-page>
<error-code>404</error-code>
<location>/common/404.jsp</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/common/500.jsp</location>
</error-page>
<error-page>
<error-code>505</error-code>
<location>/common/505.jsp</location>
</error-page>
</web-app>

  Formbean

package com.test.struts.form;
import org.apache.struts.action.ActionForm;
public class ExcelForm extends ActionForm {
private static final long serialVersionUID = -5661095366659304317L;
private String filePath;
public String getFilePath() {
return filePath;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
}

  Action

package com.test.struts.action;
import java.io.FileInputStream;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import com.test.struts.form.ExcelForm;
public class ExcelReadAction extends DispatchAction {
private ExcelForm excelForm;
private Workbook workbook;
/**
* Excel文件内容读取(2003,2007)
* @author wxb
* @param mapping
* @param form
* @param request
* @param response
* @throws ServletException
* @throws IOException
* @date 2012-04-18 14:29:14
*/
public ActionForward read(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
excelForm = (ExcelForm) form;
/**
* 服务端Excel文件验证略过.....
*/
/**
* 读取Excel文件内容.....
* 注:读取2003版本与读取2007版或更高的版本apache-poi读取文件的方式不同
* Excel中CELL常见类型
* -------------------------------------------------
* |CELL_TYPE_NUMERIC            数值(常见数字、日期等)
* |CELL_TYPE_STRING            字符串
* |CELL_TYPE_FORMULA            公式
* |CELL_TYPE_BLANK         空值(cell不为空)
* |CELL_TYPE_BOOLEAN            布尔
* |CELL_TYPE_ERROR              错误
* -------------------------------------------------
*/
try {
// 2003版本Excel(.xls)
workbook = new HSSFWorkbook(new FileInputStream(excelForm.getFilePath()));
} catch (Exception e) {
// 2007版本Excel或更高版本(.xlsx)
workbook = new XSSFWorkbook(excelForm.getFilePath());
}
// 循环sheet
for (int k = 0; k < workbook.getNumberOfSheets(); k++) {
// sheet
Sheet sheet = workbook.getSheetAt(k);
int rows = sheet.getPhysicalNumberOfRows();
// 循环行
for (int r = 0; r < rows; r++) {
// 定义row
Row row = (Row) sheet.getRow(r);
if (row != null) {
// 定义cell(列)
int cells = row.getPhysicalNumberOfCells();
// 循环列
for (int c = 0; c < cells; c++) {
Cell cell = row.getCell(c);
if (cell != null) {
String value = null;
switch (cell.getCellType()) {
case Cell.CELL_TYPE_FORMULA:
value = "FORMULA value =" + cell.getCellFormula();
break;
case Cell.CELL_TYPE_NUMERIC:
if (HSSFDateUtil.isCellDateFormatted(cell)) {
value = "DATE value = " + cell.getDateCellValue();
} else {
value = "NUMERIC value = " + cell.getNumericCellValue();
}
break;
case Cell.CELL_TYPE_STRING:
value = "STRING value = " + cell.getStringCellValue();
break;
case Cell.CELL_TYPE_BOOLEAN:
value = "BOOLEAN value = " + cell.getBooleanCellValue();
break;
default:
}
System.out.println(value);
}
}
}
}
}
return null;
}
public ExcelForm getExcelForm() {
return excelForm;
}
public void setExcelForm(ExcelForm excelForm) {
this.excelForm = excelForm;
}
}

  字符集Filter过滤器
  apache-tomcat-6.0目录-----webapps-----examples-----WEB-INF-----classes-----filters
  拷贝 SetCharacterEncodingFilter.java
  apache官方说明api文档:
  http://poi.apache.org/spreadsheet/how-to.html#xssf_sax_api
  apache功能支持Jar包结构:
  http://poi.apache.org/overview.html
  apache  poi下载地址:
  http://poi.apache.org/download.html
  例子中,使用的结构是 struts1.3  +  apache poi3.8  支持的Jar包
  struts1.3支持
DSC0000.jpg  

  apache poi3.8  支持
DSC0001.jpg

   注:
  1) 读取Excel2003与Excel2007或更高版本的方式不同
  2) 如遇到缺少 apache poi  相关支持Jar包时,可以去下面的网站去搜索:
  http://www.jarfinder.com/ 
  用于搜索各种Jar包,很好用。

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-325819-1-1.html 上篇帖子: 结合Apache和Tomcat实现集群和负载均衡[转] 下篇帖子: apache 使用 proxy 实现tomcate负载均衡(session复制)
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表