搭建环境

先新建web project ,然后Add Struts Capabilties:

下载导入导出Excel所需的jar包:

poi-3.8-20120326.jar包  :  http://poi.apache.org/download.html

1、工程目录结构

2、struts.xml


  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
  3. <struts>
  4. <package name="importexport" extends="struts-default">
  5. <action name="downloadExcelModelAction" class="com.importexport.action.DownloadExcelModelAction"></action>
  6. <action name="exportExcelAction" class="com.importexport.action.ExportExcelAction"></action>
  7. <action name="importExcelAction" class="com.importexport.action.ImportExcelAction"></action>
  8. </package>
  9. </struts>

3、web.xml


  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app version="2.5"
  3. xmlns="http://java.sun.com/xml/ns/javaee"
  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
  6. http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  7. <display-name></display-name>
  8. <welcome-file-list>
  9. <welcome-file>index.jsp</welcome-file>
  10. </welcome-file-list>
  11. <filter>
  12. <filter-name>struts2</filter-name>
  13. <filter-class>
  14. org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
  15. </filter-class>
  16. </filter>
  17. <filter-mapping>
  18. <filter-name>struts2</filter-name>
  19. <url-pattern>/*</url-pattern>
  20. </filter-mapping>
  21. </web-app>

4、导入导出Excel基础类

4.1  ExportExcel.java

4.2  ImportExcel.java


  1. package com.importexport.util;
  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.io.InputStream;
  5. import java.text.SimpleDateFormat;
  6. import java.util.ArrayList;
  7. import java.util.Date;
  8. import java.util.List;
  9. import org.apache.poi.hssf.usermodel.HSSFCell;
  10. import org.apache.poi.hssf.usermodel.HSSFDateUtil;
  11. import org.apache.poi.hssf.usermodel.HSSFRow;
  12. import org.apache.poi.hssf.usermodel.HSSFSheet;
  13. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  14. public class ImportExcel {
  15. /**
  16. * @param file 要导入的Excel文件
  17. * @param cLength 读取多少列
  18. * @return
  19. */
  20. public List<List<List<String>>> importExcel(File file,int cLength){
  21. try {
  22. InputStream xlsIs = new FileInputStream(file);
  23. HSSFWorkbook hssfWorkbook = new HSSFWorkbook(xlsIs);
  24. List<List<List<String>>> worksheetList = new ArrayList<List<List<String>>>();
  25. //循环工作簿
  26. for(int nSheet=0; nSheet < hssfWorkbook.getNumberOfSheets(); ++nSheet){
  27. HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(nSheet);
  28. if(hssfSheet == null){
  29. worksheetList.add(null);//空工作簿占位
  30. continue;
  31. }
  32. List<List<String>> workSheet = new ArrayList<List<String>>();
  33. //循环行
  34. for(int nRow=0; nRow <= hssfSheet.getLastRowNum(); ++nRow){
  35. HSSFRow hssfRow = hssfSheet.getRow(nRow);
  36. if(hssfRow == null){
  37. workSheet.add(null);//空行占位
  38. continue;
  39. }
  40. List<String> rowList = new ArrayList<String>();
  41. int len = hssfRow.getLastCellNum();
  42. len = len > cLength ? len : cLength;
  43. for(int nCell=0; nCell<len; ++nCell){
  44. HSSFCell xh = hssfRow.getCell(nCell);
  45. if(xh == null){
  46. rowList.add(null);
  47. continue;
  48. }
  49. String cellValue = getVlaue(xh);
  50. rowList.add(cellValue);
  51. }
  52. workSheet.add(rowList);//向工作簿中添加一行
  53. }
  54. worksheetList.add(workSheet);//向Excel文档中添加一个工作簿
  55. }
  56. return worksheetList;
  57. } catch (Exception e) {
  58. // TODO Auto-generated catch block
  59. e.printStackTrace();
  60. }
  61. return null;
  62. }
  63. private String getVlaue(HSSFCell xh) {
  64. // TODO Auto-generated method stub
  65. String reValue = null;
  66. if(xh.getCellType() == xh.CELL_TYPE_BOOLEAN){//返回布尔类型的值
  67. reValue = String.valueOf(xh.getBooleanCellValue());
  68. }else if(xh.getCellType() == xh.CELL_TYPE_NUMERIC){//返回数值类型的值
  69. if(HSSFDateUtil.isCellDateFormatted(xh)){
  70. SimpleDateFormat dateformat =new SimpleDateFormat("yyyy-MM-dd");
  71. Date dt = HSSFDateUtil.getJavaDate(xh.getNumericCellValue());
  72. reValue = dateformat.format(dt);
  73. }else{
  74. reValue = String.valueOf(xh.getNumericCellValue());
  75. }
  76. }else{//返回字符串类型的值
  77. reValue = String.valueOf(xh.getStringCellValue());
  78. }
  79. return reValue;
  80. }
  81. }

5、导入导出action类

5.1 DownloadExcelModelAction.java


  1. package com.importexport.action;
  2. import java.io.OutputStream;
  3. import java.util.ArrayList;
  4. import java.util.HashMap;
  5. import java.util.List;
  6. import javax.servlet.http.HttpServletResponse;
  7. import org.apache.struts2.ServletActionContext;
  8. import com.opensymphony.xwork2.ActionSupport;
  9. import com.importexport.util.ExportExcel;
  10. /**
  11. * 下载Excel模板
  12. *
  13. */
  14. public class DownloadExcelModelAction extends ActionSupport {
  15. /**
  16. * 自定义Excel模板一(最简) 下载
  17. */
  18. public void downLoadExcelOne() {
  19. try {
  20. String title = "人员信息列表";
  21. String[] headers = { "姓名", "性别", "居住地" };
  22. int[] columns = {};//从0开始计数,下拉选择数据列
  23. List<String[]> valueList = new ArrayList<String[]>();//需要下拉选择数据列的选择项
  24. HttpServletResponse response = ServletActionContext.getResponse();
  25. response.setContentType("octets/stream");
  26. String header = "自定义Excel模板一(最简).xls";
  27. header = new String(header.getBytes(), "iso-8859-1");
  28. response.addHeader("Content-Disposition", "attachment;filename="
  29. + header);
  30. OutputStream out = response.getOutputStream();
  31. ExportExcel<HashMap> exportexcel = new ExportExcel<HashMap>();
  32. exportexcel.exportExcelModel(title, headers, columns, valueList,
  33. out, null);
  34. out.close();
  35. } catch (Exception e) {
  36. // TODO Auto-generated catch block
  37. e.printStackTrace();
  38. }
  39. }
  40. /**
  41. * 自定义Excel模板二(含有下拉选择项)下载
  42. */
  43. public void downLoadExcelTwo() {
  44. try {
  45. String title = "人员信息列表";
  46. String[] headers = { "姓名", "性别", "居住地",""};
  47. int[] columns = {1,2};//从0开始计数,下拉选择数据列
  48. List<String[]> valueList = new ArrayList<String[]>();
  49. String[] sex = {"男","女"};
  50. valueList.add(sex);
  51. String[] address = {"广州","汕头","深圳","珠海"};
  52. valueList.add(address);
  53. HttpServletResponse response = ServletActionContext.getResponse();
  54. response.setContentType("octets/stream");
  55. String header = "自定义Excel模板二(含有下拉选择项).xls";
  56. header = new String(header.getBytes(), "iso-8859-1");
  57. response.addHeader("Content-Disposition", "attachment;filename="
  58. + header);
  59. OutputStream out = response.getOutputStream();
  60. ExportExcel<HashMap> exportexcel = new ExportExcel<HashMap>();
  61. exportexcel.exportExcelModel(title, headers, columns, valueList,
  62. out, null);
  63. out.close();
  64. } catch (Exception e) {
  65. // TODO Auto-generated catch block
  66. e.printStackTrace();
  67. }
  68. }
  69. /**
  70. * 自定义Excel模板三(增加security表单) 下载
  71. */
  72. public void downLoadExcelThree() {
  73. try {
  74. String title = "人员信息列表";
  75. String[] headers = { "姓名", "性别", "居住地" };
  76. int[] columns = {};//从0开始计数,下拉选择数据列
  77. List<String[]> valueList = new ArrayList<String[]>();//需要下拉选择数据列的选择项
  78. String[] security = {"测试security","测试6666"};//验证表单的展示内容
  79. HttpServletResponse response = ServletActionContext.getResponse();
  80. response.setContentType("octets/stream");
  81. String header = "自定义Excel模板三(增加security表单).xls";
  82. header = new String(header.getBytes(), "iso-8859-1");
  83. response.addHeader("Content-Disposition", "attachment;filename="
  84. + header);
  85. OutputStream out = response.getOutputStream();
  86. ExportExcel<HashMap> exportexcel = new ExportExcel<HashMap>();
  87. exportexcel.exportExcelModel(title, headers, columns, valueList,
  88. out, security);
  89. out.close();
  90. } catch (Exception e) {
  91. // TODO Auto-generated catch block
  92. e.printStackTrace();
  93. }
  94. }
  95. }

5.2 ExportExcelAction.java


  1. package com.importexport.action;
  2. import java.io.OutputStream;
  3. import java.util.ArrayList;
  4. import java.util.HashMap;
  5. import java.util.List;
  6. import javax.servlet.http.HttpServletResponse;
  7. import org.apache.commons.validator.Var;
  8. import org.apache.struts2.ServletActionContext;
  9. import com.importexport.util.ExportExcel;
  10. import com.opensymphony.xwork2.ActionSupport;
  11. /**
  12. * 导出Excel文件
  13. */
  14. public class ExportExcelAction extends ActionSupport{
  15. /**
  16. * 导出数据成Excel文件(最简)
  17. */
  18. public void exportExcelOne() {
  19. try {
  20. String title = "人员信息列表";
  21. String[] headers = { "姓名", "性别", "居住地" };
  22. String[] keys = {"name","sex","address"};//HashMap中的key值
  23. //封装要导出的数据
  24. List<HashMap<Object,Object>> dataset = new ArrayList<HashMap<Object,Object>>();
  25. for(int i = 0;i < 5;i++){
  26. HashMap map = new HashMap();
  27. map.put("name", "楚暮" + i);
  28. map.put("sex", "半魔");
  29. map.put("address", "湛离界");
  30. dataset.add(map);
  31. }
  32. HttpServletResponse response = ServletActionContext.getResponse();
  33. response.setContentType("octets/stream");
  34. String header = "导出数据成Excel文件(最简).xls";
  35. header = new String(header.getBytes(), "iso-8859-1");
  36. response.addHeader("Content-Disposition", "attachment;filename="
  37. + header);
  38. OutputStream out = response.getOutputStream();
  39. ExportExcel<HashMap> exportexcel = new ExportExcel<HashMap>();
  40. exportexcel.exportExcelList(title, headers, dataset , out, keys,null,null);
  41. out.close();
  42. } catch (Exception e) {
  43. // TODO Auto-generated catch block
  44. e.printStackTrace();
  45. }
  46. }
  47. /**
  48. * 导出数据成Excel文件(合并单元格)
  49. */
  50. public void exportExcelTwo() {
  51. try {
  52. String title = "人员信息列表";
  53. String[] headers = { "姓名", "性别", "居住地" };
  54. String[] keys = {"name","sex","address"};//HashMap中的key值
  55. //封装要导出的数据
  56. List<HashMap<Object,Object>> dataset = new ArrayList<HashMap<Object,Object>>();
  57. for(int i = 0;i < 6;i++){
  58. HashMap<Object, Object> map = new HashMap();
  59. map.put("name", "楚暮" + i);
  60. map.put("sex", "半魔");
  61. map.put("address", "湛离界");
  62. dataset.add(map);
  63. }
  64. int[] mergedCol = {1,2};//从0开始算起,合并第一列(sex)和第二列(address)
  65. //{3,1,1,1} 3+1+1+1=6   表示把前3行合并单元格,第4行合并单元格,第5行合并单元格,第6行合并单元格
  66. //{3,2,1} 3+2+1=6  表示前3行合并单元格,第4、5合并单元格,第6行合并单元格
  67. //{2,4} 2+4=6 表示前2行合并单元格,第3,4,5,6行合并单元格
  68. //{6} 表示前6行合并单元格
  69. int[] mergedL = {3,1,2};
  70. HttpServletResponse response = ServletActionContext.getResponse();
  71. response.setContentType("octets/stream");
  72. String header = "导出数据成Excel文件(合并单元格).xls";
  73. header = new String(header.getBytes(), "iso-8859-1");
  74. response.addHeader("Content-Disposition", "attachment;filename="
  75. + header);
  76. OutputStream out = response.getOutputStream();
  77. ExportExcel<HashMap> exportexcel = new ExportExcel<HashMap>();
  78. exportexcel.exportExcelList(title, headers, dataset , out, keys,mergedCol,mergedL);
  79. out.close();
  80. } catch (Exception e) {
  81. // TODO Auto-generated catch block
  82. e.printStackTrace();
  83. }
  84. }
  85. }

5.3 ImportExcelAction.java


  1. package com.importexport.action;
  2. import com.importexport.util.ImportExcel;
  3. import com.opensymphony.xwork2.ActionSupport;
  4. import java.io.File;
  5. import java.util.List;
  6. import org.apache.struts2.ServletActionContext;
  7. /**
  8. * 导入Excel文件
  9. */
  10. public class ImportExcelAction extends ActionSupport{
  11. /**
  12. * 导入Excel文件
  13. */
  14. public void importExcel(){
  15. ImportExcel importExcel = new ImportExcel();
  16. String path = ServletActionContext.getRequest().getRealPath("/");
  17. File excelfile = new File(path + "自定义Excel模板二(含有下拉选择项).xls");
  18. List<List<List<String>>> excelAll = importExcel.importExcel(excelfile, 3);//3 : 读取3列
  19. //解析打印数据
  20. List<List<String>> excelSheet = excelAll.get(0);
  21. for(List<String> excelRow : excelSheet){
  22. System.out.println(excelRow.get(0) + "-" + excelRow.get(1) + "-" + excelRow.get(2));
  23. }
  24. }
  25. }

6、index.jsp


  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
  2. <%
  3. String path = request.getContextPath();
  4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
  5. %>
  6. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  7. <html>
  8. <head>
  9. <title>导入导出Excel</title>
  10. </head>
  11. <body>
  12. <h2>导出Excel模板</h2>
  13. <a href="downloadExcelModelAction!downLoadExcelOne.action">下载自定义Excel模板一(最简)</a>
  14. <a href="downloadExcelModelAction!downLoadExcelTwo.action">下载自定义Excel模板二(含有下拉选择项)</a>
  15. <a href="downloadExcelModelAction!downLoadExcelThree.action">下载自定义Excel模板三(增加security表单)</a>
  16. <h2>导出</h2>
  17. <a href="exportExcelAction!exportExcelOne.action">导出数据成Excel文件(最简)</a>
  18. <a href="exportExcelAction!exportExcelTwo.action">导出数据成Excel文件(合并单元格)</a>
  19. <h2>导入</h2>
  20. <a href="importExcelAction!importExcel.action">导入Excel文件</a>
  21. </body>
  22. </html>

7、效果截图

要导入的Excel数据

读取Excel数据,在控制台打印相关数据

附件源码:

下载地址:https://gitee.com/KingXin666/ImportExport

导入导出Excel文件的更多相关文章

  1. 【转】 (C#)利用Aspose.Cells组件导入导出excel文件

    Aspose.Cells组件可以不依赖excel来导入导出excel文件: 导入: public static System.Data.DataTable ReadExcel(String strFi ...

  2. (C#)利用Aspose.Cells组件导入导出excel文件

    Aspose.Cells组件可以不依赖excel来导入导出excel文件: 导入: public static System.Data.DataTable ReadExcel(String strFi ...

  3. ASP.NET Core导入导出Excel文件

    ASP.NET Core导入导出Excel文件 希望在ASP.NET Core中导入导出Excel文件,在网上搜了一遍,基本都是使用EPPlus插件,EPPlus挺好用,但商用需要授权,各位码友若有好 ...

  4. java中使用poi导入导出excel文件_并自定义日期格式

    Apache POI项目的使命是创造和保持java API操纵各种文件格式基于Office Open XML标准(OOXML)和微软的OLE复合文档格式(OLE2)2.总之,你可以读写Excel文件使 ...

  5. C# 导入导出excel文件案例

    个人总结导出excel报表的案例: //导出报表 protected void btnExport_Click(object sender, EventArgs e) { List<ProOut ...

  6. java导入导出Excel文件

    package poi.excel; import java.io.IOException; import java.io.InputStream; import java.io.OutputStre ...

  7. 简单回顾NPOI导入导出excel文件

    当前环境.net4.0 去官方下下载:  NOPI官网 关于NOPI的详细,这里就不再介绍. 在项目中,我们只需引入  NPOI.dll  就可以了. 接下来..................... ...

  8. SpringMVC 导入导出Excel文件

    /**  * 下载Excel模板 创建一个新的文件用于下载,创建的文件放在缓存中  *   * @param request  * @param response  */ /*  * @Request ...

  9. php中导入导出excel的原理

    在php中我们要经常导入导出excel文件,方便后台管理.那么php导入和导出excel的原理到底是什么呢?excel分为两大版本excel2007(后缀.xlsx).excel2003(后缀.xls ...

随机推荐

  1. Example of Abstract Class

    The Vehicle class has abstract members that must be implemented by the Car class or any other class ...

  2. less中使用calc

    css3中可以使用calc()来实现自适应布局 例如:width:“calc(100%  - 25px)” width: calc(expression); ==> expression是一个表 ...

  3. gcd和lcm模板

    long long gcd(long long b,long long c)//计算最大公约数{ return c==0?b:gcd(c,b%c);} long long lcm(long long ...

  4. tomcat 配置成服务

    1.下载Zip版Tomcat;选择:32-bit Windows zip(pgp,md5)下载解压文件到指定目录,如:D:/ProgramFiles/Tomcat6 进入D:/ProgramFiles ...

  5. Django + nginx + uswgi 的部署总结

    一.引言 自己小组内写了一个网站,需要部署到远程服务器,搜索了好多资料,但是大部分资料都比较繁琐,并且没有一个教程能够直接从头到尾适合,在部署过程中,我是按照很多教程然后综合试验着逐渐部署成功,其中有 ...

  6. (转载)Peter Norvig:十年学会编程

    作者 Peter Norvig 是计算机科学家,Google 的研究总监.在本文中,Peter Norvig会告诉你:为什么急功近利地学习软件开发技术是没效果滴? ================华丽 ...

  7. 【linux】ARM板子开启浮点和neon加速

    参考 1. ARM平台NEON指令的编译和优化; 2. 交叉编译器 arm-linux-gnueabi 和 arm-linux-gnueabihf 的区别; 3. https://blog.csdn. ...

  8. SQLAlchemy中表结构的一对多

    from flask import Flask from flask_sqlalchemy import SQLAlchemy import pymysql pymysql.install_as_My ...

  9. s21day01 python笔记

    s21day01 python笔记 一.计算机基础 计算机的初步认识 用户:人 软件:QQ.浏览器等 解释器/编译器/虚拟机:java解释器.python解释器等 操作系统 硬件:CPU.内存.硬盘. ...

  10. select的width和input的width

    select的width包括了border,而input不包括