导入导出Excel文件
搭建环境
先新建web project ,然后Add Struts Capabilties:
下载导入导出Excel所需的jar包:
poi-3.8-20120326.jar包 : http://poi.apache.org/download.html
1、工程目录结构
2、struts.xml
- <?xml version="1.0" encoding="UTF-8" ?>
- <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
- <struts>
- <package name="importexport" extends="struts-default">
- <action name="downloadExcelModelAction" class="com.importexport.action.DownloadExcelModelAction"></action>
- <action name="exportExcelAction" class="com.importexport.action.ExportExcelAction"></action>
- <action name="importExcelAction" class="com.importexport.action.ImportExcelAction"></action>
- </package>
- </struts>
3、web.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app version="2.5"
- xmlns="http://java.sun.com/xml/ns/javaee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
- http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
- <display-name></display-name>
- <welcome-file-list>
- <welcome-file>index.jsp</welcome-file>
- </welcome-file-list>
- <filter>
- <filter-name>struts2</filter-name>
- <filter-class>
- org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
- </filter-class>
- </filter>
- <filter-mapping>
- <filter-name>struts2</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
- </web-app>
4、导入导出Excel基础类
4.1 ExportExcel.java
4.2 ImportExcel.java
- package com.importexport.util;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.InputStream;
- import java.text.SimpleDateFormat;
- import java.util.ArrayList;
- import java.util.Date;
- import java.util.List;
- import org.apache.poi.hssf.usermodel.HSSFCell;
- import org.apache.poi.hssf.usermodel.HSSFDateUtil;
- import org.apache.poi.hssf.usermodel.HSSFRow;
- import org.apache.poi.hssf.usermodel.HSSFSheet;
- import org.apache.poi.hssf.usermodel.HSSFWorkbook;
- public class ImportExcel {
- /**
- * @param file 要导入的Excel文件
- * @param cLength 读取多少列
- * @return
- */
- public List<List<List<String>>> importExcel(File file,int cLength){
- try {
- InputStream xlsIs = new FileInputStream(file);
- HSSFWorkbook hssfWorkbook = new HSSFWorkbook(xlsIs);
- List<List<List<String>>> worksheetList = new ArrayList<List<List<String>>>();
- //循环工作簿
- for(int nSheet=0; nSheet < hssfWorkbook.getNumberOfSheets(); ++nSheet){
- HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(nSheet);
- if(hssfSheet == null){
- worksheetList.add(null);//空工作簿占位
- continue;
- }
- List<List<String>> workSheet = new ArrayList<List<String>>();
- //循环行
- for(int nRow=0; nRow <= hssfSheet.getLastRowNum(); ++nRow){
- HSSFRow hssfRow = hssfSheet.getRow(nRow);
- if(hssfRow == null){
- workSheet.add(null);//空行占位
- continue;
- }
- List<String> rowList = new ArrayList<String>();
- int len = hssfRow.getLastCellNum();
- len = len > cLength ? len : cLength;
- for(int nCell=0; nCell<len; ++nCell){
- HSSFCell xh = hssfRow.getCell(nCell);
- if(xh == null){
- rowList.add(null);
- continue;
- }
- String cellValue = getVlaue(xh);
- rowList.add(cellValue);
- }
- workSheet.add(rowList);//向工作簿中添加一行
- }
- worksheetList.add(workSheet);//向Excel文档中添加一个工作簿
- }
- return worksheetList;
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return null;
- }
- private String getVlaue(HSSFCell xh) {
- // TODO Auto-generated method stub
- String reValue = null;
- if(xh.getCellType() == xh.CELL_TYPE_BOOLEAN){//返回布尔类型的值
- reValue = String.valueOf(xh.getBooleanCellValue());
- }else if(xh.getCellType() == xh.CELL_TYPE_NUMERIC){//返回数值类型的值
- if(HSSFDateUtil.isCellDateFormatted(xh)){
- SimpleDateFormat dateformat =new SimpleDateFormat("yyyy-MM-dd");
- Date dt = HSSFDateUtil.getJavaDate(xh.getNumericCellValue());
- reValue = dateformat.format(dt);
- }else{
- reValue = String.valueOf(xh.getNumericCellValue());
- }
- }else{//返回字符串类型的值
- reValue = String.valueOf(xh.getStringCellValue());
- }
- return reValue;
- }
- }
5、导入导出action类
5.1 DownloadExcelModelAction.java
- package com.importexport.action;
- import java.io.OutputStream;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.List;
- import javax.servlet.http.HttpServletResponse;
- import org.apache.struts2.ServletActionContext;
- import com.opensymphony.xwork2.ActionSupport;
- import com.importexport.util.ExportExcel;
- /**
- * 下载Excel模板
- *
- */
- public class DownloadExcelModelAction extends ActionSupport {
- /**
- * 自定义Excel模板一(最简) 下载
- */
- public void downLoadExcelOne() {
- try {
- String title = "人员信息列表";
- String[] headers = { "姓名", "性别", "居住地" };
- int[] columns = {};//从0开始计数,下拉选择数据列
- List<String[]> valueList = new ArrayList<String[]>();//需要下拉选择数据列的选择项
- HttpServletResponse response = ServletActionContext.getResponse();
- response.setContentType("octets/stream");
- String header = "自定义Excel模板一(最简).xls";
- header = new String(header.getBytes(), "iso-8859-1");
- response.addHeader("Content-Disposition", "attachment;filename="
- + header);
- OutputStream out = response.getOutputStream();
- ExportExcel<HashMap> exportexcel = new ExportExcel<HashMap>();
- exportexcel.exportExcelModel(title, headers, columns, valueList,
- out, null);
- out.close();
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- /**
- * 自定义Excel模板二(含有下拉选择项)下载
- */
- public void downLoadExcelTwo() {
- try {
- String title = "人员信息列表";
- String[] headers = { "姓名", "性别", "居住地",""};
- int[] columns = {1,2};//从0开始计数,下拉选择数据列
- List<String[]> valueList = new ArrayList<String[]>();
- String[] sex = {"男","女"};
- valueList.add(sex);
- String[] address = {"广州","汕头","深圳","珠海"};
- valueList.add(address);
- HttpServletResponse response = ServletActionContext.getResponse();
- response.setContentType("octets/stream");
- String header = "自定义Excel模板二(含有下拉选择项).xls";
- header = new String(header.getBytes(), "iso-8859-1");
- response.addHeader("Content-Disposition", "attachment;filename="
- + header);
- OutputStream out = response.getOutputStream();
- ExportExcel<HashMap> exportexcel = new ExportExcel<HashMap>();
- exportexcel.exportExcelModel(title, headers, columns, valueList,
- out, null);
- out.close();
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- /**
- * 自定义Excel模板三(增加security表单) 下载
- */
- public void downLoadExcelThree() {
- try {
- String title = "人员信息列表";
- String[] headers = { "姓名", "性别", "居住地" };
- int[] columns = {};//从0开始计数,下拉选择数据列
- List<String[]> valueList = new ArrayList<String[]>();//需要下拉选择数据列的选择项
- String[] security = {"测试security","测试6666"};//验证表单的展示内容
- HttpServletResponse response = ServletActionContext.getResponse();
- response.setContentType("octets/stream");
- String header = "自定义Excel模板三(增加security表单).xls";
- header = new String(header.getBytes(), "iso-8859-1");
- response.addHeader("Content-Disposition", "attachment;filename="
- + header);
- OutputStream out = response.getOutputStream();
- ExportExcel<HashMap> exportexcel = new ExportExcel<HashMap>();
- exportexcel.exportExcelModel(title, headers, columns, valueList,
- out, security);
- out.close();
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
5.2 ExportExcelAction.java
- package com.importexport.action;
- import java.io.OutputStream;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.List;
- import javax.servlet.http.HttpServletResponse;
- import org.apache.commons.validator.Var;
- import org.apache.struts2.ServletActionContext;
- import com.importexport.util.ExportExcel;
- import com.opensymphony.xwork2.ActionSupport;
- /**
- * 导出Excel文件
- */
- public class ExportExcelAction extends ActionSupport{
- /**
- * 导出数据成Excel文件(最简)
- */
- public void exportExcelOne() {
- try {
- String title = "人员信息列表";
- String[] headers = { "姓名", "性别", "居住地" };
- String[] keys = {"name","sex","address"};//HashMap中的key值
- //封装要导出的数据
- List<HashMap<Object,Object>> dataset = new ArrayList<HashMap<Object,Object>>();
- for(int i = 0;i < 5;i++){
- HashMap map = new HashMap();
- map.put("name", "楚暮" + i);
- map.put("sex", "半魔");
- map.put("address", "湛离界");
- dataset.add(map);
- }
- HttpServletResponse response = ServletActionContext.getResponse();
- response.setContentType("octets/stream");
- String header = "导出数据成Excel文件(最简).xls";
- header = new String(header.getBytes(), "iso-8859-1");
- response.addHeader("Content-Disposition", "attachment;filename="
- + header);
- OutputStream out = response.getOutputStream();
- ExportExcel<HashMap> exportexcel = new ExportExcel<HashMap>();
- exportexcel.exportExcelList(title, headers, dataset , out, keys,null,null);
- out.close();
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- /**
- * 导出数据成Excel文件(合并单元格)
- */
- public void exportExcelTwo() {
- try {
- String title = "人员信息列表";
- String[] headers = { "姓名", "性别", "居住地" };
- String[] keys = {"name","sex","address"};//HashMap中的key值
- //封装要导出的数据
- List<HashMap<Object,Object>> dataset = new ArrayList<HashMap<Object,Object>>();
- for(int i = 0;i < 6;i++){
- HashMap<Object, Object> map = new HashMap();
- map.put("name", "楚暮" + i);
- map.put("sex", "半魔");
- map.put("address", "湛离界");
- dataset.add(map);
- }
- int[] mergedCol = {1,2};//从0开始算起,合并第一列(sex)和第二列(address)
- //{3,1,1,1} 3+1+1+1=6 表示把前3行合并单元格,第4行合并单元格,第5行合并单元格,第6行合并单元格
- //{3,2,1} 3+2+1=6 表示前3行合并单元格,第4、5合并单元格,第6行合并单元格
- //{2,4} 2+4=6 表示前2行合并单元格,第3,4,5,6行合并单元格
- //{6} 表示前6行合并单元格
- int[] mergedL = {3,1,2};
- HttpServletResponse response = ServletActionContext.getResponse();
- response.setContentType("octets/stream");
- String header = "导出数据成Excel文件(合并单元格).xls";
- header = new String(header.getBytes(), "iso-8859-1");
- response.addHeader("Content-Disposition", "attachment;filename="
- + header);
- OutputStream out = response.getOutputStream();
- ExportExcel<HashMap> exportexcel = new ExportExcel<HashMap>();
- exportexcel.exportExcelList(title, headers, dataset , out, keys,mergedCol,mergedL);
- out.close();
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
5.3 ImportExcelAction.java
- package com.importexport.action;
- import com.importexport.util.ImportExcel;
- import com.opensymphony.xwork2.ActionSupport;
- import java.io.File;
- import java.util.List;
- import org.apache.struts2.ServletActionContext;
- /**
- * 导入Excel文件
- */
- public class ImportExcelAction extends ActionSupport{
- /**
- * 导入Excel文件
- */
- public void importExcel(){
- ImportExcel importExcel = new ImportExcel();
- String path = ServletActionContext.getRequest().getRealPath("/");
- File excelfile = new File(path + "自定义Excel模板二(含有下拉选择项).xls");
- List<List<List<String>>> excelAll = importExcel.importExcel(excelfile, 3);//3 : 读取3列
- //解析打印数据
- List<List<String>> excelSheet = excelAll.get(0);
- for(List<String> excelRow : excelSheet){
- System.out.println(excelRow.get(0) + "-" + excelRow.get(1) + "-" + excelRow.get(2));
- }
- }
- }
6、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</title>
- </head>
- <body>
- <h2>导出Excel模板</h2>
- <a href="downloadExcelModelAction!downLoadExcelOne.action">下载自定义Excel模板一(最简)</a>
- <a href="downloadExcelModelAction!downLoadExcelTwo.action">下载自定义Excel模板二(含有下拉选择项)</a>
- <a href="downloadExcelModelAction!downLoadExcelThree.action">下载自定义Excel模板三(增加security表单)</a>
- <h2>导出</h2>
- <a href="exportExcelAction!exportExcelOne.action">导出数据成Excel文件(最简)</a>
- <a href="exportExcelAction!exportExcelTwo.action">导出数据成Excel文件(合并单元格)</a>
- <h2>导入</h2>
- <a href="importExcelAction!importExcel.action">导入Excel文件</a>
- </body>
- </html>
7、效果截图
要导入的Excel数据
读取Excel数据,在控制台打印相关数据
附件源码:
导入导出Excel文件的更多相关文章
- 【转】 (C#)利用Aspose.Cells组件导入导出excel文件
Aspose.Cells组件可以不依赖excel来导入导出excel文件: 导入: public static System.Data.DataTable ReadExcel(String strFi ...
- (C#)利用Aspose.Cells组件导入导出excel文件
Aspose.Cells组件可以不依赖excel来导入导出excel文件: 导入: public static System.Data.DataTable ReadExcel(String strFi ...
- ASP.NET Core导入导出Excel文件
ASP.NET Core导入导出Excel文件 希望在ASP.NET Core中导入导出Excel文件,在网上搜了一遍,基本都是使用EPPlus插件,EPPlus挺好用,但商用需要授权,各位码友若有好 ...
- java中使用poi导入导出excel文件_并自定义日期格式
Apache POI项目的使命是创造和保持java API操纵各种文件格式基于Office Open XML标准(OOXML)和微软的OLE复合文档格式(OLE2)2.总之,你可以读写Excel文件使 ...
- C# 导入导出excel文件案例
个人总结导出excel报表的案例: //导出报表 protected void btnExport_Click(object sender, EventArgs e) { List<ProOut ...
- java导入导出Excel文件
package poi.excel; import java.io.IOException; import java.io.InputStream; import java.io.OutputStre ...
- 简单回顾NPOI导入导出excel文件
当前环境.net4.0 去官方下下载: NOPI官网 关于NOPI的详细,这里就不再介绍. 在项目中,我们只需引入 NPOI.dll 就可以了. 接下来..................... ...
- SpringMVC 导入导出Excel文件
/** * 下载Excel模板 创建一个新的文件用于下载,创建的文件放在缓存中 * * @param request * @param response */ /* * @Request ...
- php中导入导出excel的原理
在php中我们要经常导入导出excel文件,方便后台管理.那么php导入和导出excel的原理到底是什么呢?excel分为两大版本excel2007(后缀.xlsx).excel2003(后缀.xls ...
随机推荐
- kbmMW授权管理解析(The kbmMW Authorization manager explained)
从kbmMW v.4.40开始,引入了一个新的非常灵活的授权管理器. 它的目的是为开发人员提供为用户定义资源权限的功能,这是一个可选功能,将现有的授权事件驱动方案内置到kbmMW中,使授权开发任务更容 ...
- laravel 部署 前后端分离
1. iis服务器配置(web.config): <configuration> <system.webServer> <rewrite> <rules> ...
- linux command1
#列出指定用户(当前用户)的组信息 groups #将指定的用户添加(-a)到指定的组内(改组必须已经存在)或指定用户从指定的组中删除(-d) gpasswd –a/-d username grou ...
- win7英文版
下载个系统,不是一堆木马,就是一堆病毒:相对来说,我还是倾向于相信国外的镜像. https://pcriver.com/operating-systems/windows-7-ultimate-iso ...
- Oracle查询行对应block_id,file_id
select id,rowid, dbms_rowid.rowid_object(rowid) object#, dbms_rowid.rowid_relative_fno(rowid) file#, ...
- 字符串(text)格式的html代码文本转为DOM对象
/*字符串转dom对象*/ window.strimgTurnDom = function(txt) { try //Internet Explorer { xmlDoc=new ActiveXObj ...
- django额外参数的传递和url命名
django额外参数的传递 path方法:path(route, view, kwargs=None, name=None) path方法可以传递入一个额外参数的字典参数(kwarg),字典里的值就会 ...
- [Codeforces Round #492 (Div. 1) ][B. Suit and Tie]
http://codeforces.com/problemset/problem/995/B 题目大意:给一个长度为2*n的序列,分别有2个1,2,3,...n,相邻的位置可以进行交换,求使所有相同的 ...
- 20165313 《Java程序设计》第七周学习总结
教材学习总结 1.下载安装MySQL数据库管理系统. 2.MySQL数据库基本操作. 3.利用JAVA程序对MySQL数据库系统进行查找,更新,添加和删除操作. 学习中的问题与解决方案 1.运行书上安 ...
- Vim+Ctags+Cscope安装
对比了下,感觉还是Vim比较专业. 一:使用说明: ‘/’查找忽略大小写,比如需要查找“book”,当输入/b的时候会自动找到第一个以"b"开头的单词 实现C程序的缩减 查询中自由 ...