导入导出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 ...
随机推荐
- python-tornado和django优缺点
Django优点: 大和全(重量级框架)自带orm,template,view 需要的功能也可以去找第三方的app注重高效开发全自动化的管理后台(只需要使用起ORM,做简单的定义,就能自动生成数据库结 ...
- 2019-04-08-day027-网络编程基础
网络编程 基于同一台机器上的多个程序之间通信 可以基于文件 基于多台机器之间的通信 可以基于网络 web程序两种架构完成的: C/S :client(客户端) server(服务端) B/S :bro ...
- async/await学习笔记
async/await 的目的是简化使用 promises 的写法. 让我们来看看下面的例子: // 一个标准的 JavaScript 函数 function getNumber1() { r ...
- phpcms 操作数据库 增删改查
数据库的其他类继承的都是libs/class/model.class.php 这里面有写好的操作数据库的常用方法 1.增 insert($data, $return_insert_id = false ...
- ANDROID init进程
init简要 init是Android上启动的第一个用户态进程. 执行序列是: start_kernel() -> rest_init() -> kernel_init() -> i ...
- 无重复字符的最长子串-LeetCode-第3题-C++
题目:无重复字符的最长子串 题目描述:给定一个字符串,找出不含有重复字符的最长子串的长度. 最长不重复子串可能有很多个,但是其长度只有一种. 方法一:暴力搜索法 方法二:滑动窗口 哈希表:要查找一个元 ...
- Python中的filter()函数的用法
转载自:脚本之家 Python内建的filter()函数用于过滤序列. 和map()类似,filter()也接收一个函数和一个序列.和map()不同的时,filter()把传入的函数依次作用于每个元素 ...
- 百练6247-过滤多余的空格-2015正式B题
B:过滤多余的空格 总时间限制: 1000ms 内存限制: 65536kB 描述 一个句子中也许有多个连续空格,过滤掉多余的空格,只留下一个空格. 输入 一行,一个字符串(长度不超过200),句子的 ...
- input标签(文本域和文件域)
单行文本域: <form> <input type="text" name="..." ....../> </form> 属 ...
- cell-augmented
https://zhuanlan.zhihu.com/p/33147353 https://blog.csdn.net/thm225679/article/details/79689008 https ...