导入导出Excel文件

时间:2023-03-09 21:57:51
导入导出Excel文件

搭建环境

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

导入导出Excel文件

导入导出Excel文件

导入导出Excel文件

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

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

1、工程目录结构

导入导出Excel文件

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

导入导出Excel文件

导入导出Excel文件导入导出Excel文件

导入导出Excel文件

导入导出Excel文件

导入导出Excel文件

导入导出Excel文件

导入导出Excel文件

导入导出Excel文件

导入导出Excel文件

导入导出Excel文件

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文件

导入导出Excel文件

导入导出Excel文件

导入导出Excel文件

导入导出Excel文件

要导入的Excel数据

导入导出Excel文件

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

导入导出Excel文件

附件源码:

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