`
wxb_j2ee
  • 浏览: 137708 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

apache poi 读取Excel文件内容(2003,2007)

阅读更多

很久没记录了,前一段做了个只读取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" onsubmit="return importExcel();">
	  	<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支持

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 apache poi3.8  支持

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 注:

 

1) 读取Excel2003与Excel2007或更高版本的方式不同

 

2) 如遇到缺少 apache poi  相关支持Jar包时,可以去下面的网站去搜索:

 

http://www.jarfinder.com/ 

 

用于搜索各种Jar包,很好用。

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  • Test.7z (26.1 KB)
  • 下载次数: 16
分享到:
评论

相关推荐

    apache POI 读取 Excel

    apache poi 读取 Excel 的 jar 包 博文链接:https://wxinpeng.iteye.com/blog/231895

    poi读取excel文件

    标题提到的"poi读取excel文件",指的是使用Apache POI库来处理Excel数据。在最新的版本中,POI引入了更高效和强大的功能,使得处理Excel文件变得更加方便。 描述中提到了"最新版poi相关的6个jar包",这些jar包是...

    Apache poi 操作 excel 文件压缩包

    在Java环境中,Apache POI 提供了一套API,使得开发者能够创建、修改和读取Excel文件。这个压缩包包含了Apache POI库的多个版本及其依赖库,如ooxml-schemas、xmlbeans等,用于支持对Excel文件的OOXML(Office Open ...

    apache POI文件读写excel

    3. **读取Excel文件** - 使用`WorkbookFactory`创建`Workbook`对象,这可以是HSSFWorkbook(HSSF)或XSSFWorkbook(XSSF)。 - 通过`Workbook`获取`Sheet`对象,表示工作表。 - `Sheet`中包含多个`Row`,每个`Row...

    Java使用apache POI读取Excel2007以上代码以及所需jar包

    本文将详细介绍如何使用Apache POI库来读取Excel 2007及以上版本(即XLSX格式)的文件,并提供所需的jar包信息。 首先,要使用Apache POI读取XLSX文件,你需要确保引入了正确的依赖。Apache POI项目提供了多个组件...

    POI读取Excel带格式数据

    标题 "POI读取Excel带格式数据" 涉及到的是Apache POI库在Java中的使用,这个库允许开发者处理Microsoft Office格式的文件,包括Excel。Apache POI是一个开源项目,提供了API来读取、写入和修改Excel文档。在本场景...

    poi读取excel文件实例(兼容excel2007)

    在“poi读取excel文件实例”中,我们将讨论如何使用Apache POI API来读取和操作Excel 2007文件。以下是一些关键知识点: 1. **创建工作簿对象**:首先,你需要通过`WorkbookFactory`类的`create()`方法打开或创建一...

    poi读取excel2007和2003兼容工具例子

    在这个"poi读取excel2007和2003兼容工具例子"中,我们将探讨如何使用POI来读取不同版本的Excel文件,特别是Excel 2003(.xls)和Excel 2007及更高版本(.xlsx)。 1. **Apache POI库**:Apache POI是Apache软件基金...

    POI读取excel的内容.zip

    本教程将详细讲解如何使用Apache POI库来读取Excel文件的内容。 首先,为了在Java项目中使用Apache POI,我们需要通过Maven进行依赖管理。在`pom.xml`文件中添加以下依赖: ```xml &lt;groupId&gt;org.apache.poi ...

    java POI读取excel文件数据

    在这个场景中,我们将详细探讨如何使用Java POI读取Excel文件中的数据,包括获取总行数、列数、单元格内容、合并单元格、行高、列宽以及图片等信息。 首先,确保在项目中已经引入了Apache POI的依赖库。如果你使用...

    Java用poi读取excel文件

    Java 使用 POI 读取 Excel 文件 ...使用 POI 读取 Excel 文件非常简单,只需要引入 POI 的 jar 包,并使用相应的类和方法来访问 Excel 文件的内容。这样,我们可以轻松地在 Java 程序中读取和处理 Excel 文件的内容。

    利用POI读取excel写入到word

    以上就是使用Apache POI读取Excel数据并写入Word的基本流程。在实际应用中,你可能需要处理更复杂的情况,比如合并单元格、处理公式、格式转换等,这都需要对POI API有更深入的理解。同时,为了提高性能,可以考虑...

    poi读取Excel2007文件

    标题中的“poi读取Excel2007文件”指的是使用Apache POI库来处理Microsoft Office Open XML (OOXML) 格式的Excel文件,也就是.xlsx格式。Apache POI是Apache软件基金会的一个开源项目,它提供了Java API,使得开发者...

    POI读取2007 Excel文件

    标题中的“POI读取2007 Excel文件”指的是使用Apache POI库来解析和操作Microsoft Office Open XML (OOXML)格式的Excel文件,这种格式通常以.xlsx为扩展名。Apache POI是一个流行的Java库,它允许开发人员在Java应用...

    Apache POI库jar文件

    这些API可以帮助开发人员处理不同类型的Office文档,例如HSSF可以处理Excel 97-2003格式的电子表格,XSSF可以处理Excel 2007及以上版本的电子表格。 支持多种数据类型:Apache POI库支持多种数据类型,包括字符串...

    poi读取大文件Excel,使用xml格式解析,速度实测50mb文件13s,可指定sheet页内容,带工具类和测试类

    以上就是关于使用Apache POI的XSSFEventUserModel API解析大文件Excel的关键知识点,以及如何指定读取特定sheet页内容的概述。通过这样的方法,即使面对几十MB甚至更大的Excel文件,也能在较短时间内完成高效读取。

    POI 读取Excel文件

    - POI 不支持读取 .xls 文件(Excel 97-2003 格式),除非使用 HSSFWorkbook 类,但不推荐,因为 .xlsx 格式更现代且兼容性更好。 - 处理大型文件时,要特别注意内存管理,避免因数据量过大导致 OutOfMemoryError...

    POI读取EXCEL教程

    读取Excel文件使用HSSF的usermodel API非常直观。首先,你需要创建一个`InputStream`,然后实例化`HSSFWorkbook`: ```java InputStream myxls = new FileInputStream("workbook.xls"); HSSFWorkbook wb = new ...

Global site tag (gtag.js) - Google Analytics