`

struts poi导入导出excel

阅读更多
1.action的写法

Java代码
import java.io.*;  
import java.sql.*;  
import java.util.ArrayList;  
 
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
 
import org.apache.poi.hssf.usermodel.*;  
import org.apache.struts.action.*;  
import org.apache.struts.upload.FormFile;  
import org.apache.commons.beanutils.BeanUtils;  
 
public class Action {  
/**//* 
  * 把数据库中的字段导入到Excel ,并生成Excel文档 
  **/ 
public ActionForward getDownload(ActionMapping actionMapping,  
   ActionForm actionForm, HttpServletRequest request,  
   HttpServletResponse response) throws Exception {  
  Form fm = (Form) actionForm;  
  // Excel 文件存放在服务器的相对路径下  
  String outputFile = request.getRealPath("/tmp/Excel.xls");  
    
  try {  
   // 创建新的Excel 工作簿  
   HSSFWorkbook workbook = new HSSFWorkbook();  
   // 在Excel 工作簿中建一工作表  
   HSSFSheet sheet = workbook.createSheet("Sheet1");  
   // 设置单元格格式(文本)  
   HSSFCellStyle cellStyle = workbook.createCellStyle();  
   cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("@"));  
     
   // 在索引0的位置创建行(第一行)  
   HSSFRow row = sheet.createRow((short) 0);  
     
   HSSFCell cell1 = row.createCell((short) 0);// 第一列  
   HSSFCell cell2 = row.createCell((short) 1);  
   HSSFCell cell3 = row.createCell((short) 2);  
   // 定义单元格为字符串类型  
   cell1.setCellType(HSSFCell.CELL_TYPE_STRING);  
   cell2.setCellType(HSSFCell.CELL_TYPE_STRING);  
   cell3.setCellType(HSSFCell.CELL_TYPE_STRING);  
     
   cell1.setEncoding(HSSFCell.ENCODING_UTF_16);  
   cell2.setEncoding(HSSFCell.ENCODING_UTF_16);  
   cell3.setEncoding(HSSFCell.ENCODING_UTF_16);  
   // 在单元格中输入数据  
   cell1.setCellValue("姓名");  
   cell2.setCellValue("性别");  
   cell3.setCellValue("年龄");  
     
   Connection connection = session.connection();  
     
   String sql = "Select t.name, t.sex, t.age from table t where t.sex = ?";  
     
   try {  
    PreparedStatement ps = connection.prepareStatement(sql);  
    ps.setString(1, fm.getSex());// 传入查询条件  
    ResultSet rs = ps.executeQuery();// 查询结果存入rs  
    connection.commit();// 执行SQL  
      
    while (rs.next()) {  
    //设置j行从第二行开始  
     int j = 1;  
     row = sheet.createRow((short) j);  
     //设置i列从第二列开始  
     for (int i = 1; i <= 3; i++) {  
      HSSFCell cell = row.createCell((short) (i-1));  
      // 设置单元格格式  
      cell.setCellStyle(cellStyle);  
      cell.setCellType(HSSFCell.CELL_TYPE_STRING);  
      cell.setEncoding(HSSFCell.ENCODING_UTF_16);  
      cell.setCellValue(rs.getString(i));  
     }  
       
     j++;  
    }  
      
    request.setAttribute("message", "文件生成成功!");  
   } catch (SQLException e) {  
    request.setAttribute("message", "创建文件失败!");  
    e.printStackTrace();  
   }  
   // 删除路径下同名的Excel 文件  
   File path = new File(outputFile);  
   path.delete();  
     
   // 新建一输出文件流  
   FileOutputStream fOut = new FileOutputStream(outputFile);  
   // 把相应的Excel 工作簿存盘  
   workbook.write(fOut);  
   // 操作结束,关闭文件  
   fOut.flush();  
   fOut.close();  
    //该处如果Excel过大会影响效率,谁有好的想法可以提出来参考(不过从页面下载完后就会清空)  
   request.getSession().setAttribute("Download", outputFile);  
     
  } catch (Exception ioexception) {  
   request.setAttribute("message", "创建文件失败!");  
   return actionMapping.findForward("outJSP");  
  }  
    
  return actionMapping.findForward("outJSP");  
}  
   
/**//* 
  * 从Excel文件中读取数据,并导入到数据库中 
  **/ 
  public ActionForward getUpload(ActionMapping actionMapping,  
   ActionForm actionForm, HttpServletRequest request,  
   HttpServletResponse response) throws Exception {  
  // 获取excel 文件  
  Form fm = (Form) actionForm;  
  FormFile formfile = fm.getUploadfile();  
  InputStream inputstream = formfile.getInputStream();  
  fm.clear();// 清空  
  Session session = HibernateSession.currentSession();  
  ArrayList list = new ArrayList();  
  int input = 0; //导入记数  
  String name = null;  
  String sex = null;  
  String age = null;  
    
  try {  
   //通过得到的文件输入流inputstream创建一个HSSFWordbook对象  
         HSSFWorkbook hssfworkbook = new HSSFWorkbook(inputstream);  
         HSSFSheet hssfsheet = hssfworkbook.getSheetAt(0);//第一个工作表  
   HSSFRow hssfrow = hssfsheet.getRow(0);//第一行  
     
   //遍历该表格中所有的工作表,i表示工作表的数量 getNumberOfSheets表示工作表的总数  
            for (int i = 0; i < hssfworkbook.getNumberOfSheets(); i++) {  
             hssfsheet = hssfworkbook.getSheetAt(i);  
               
             //遍历该行所有的行,j表示行数 getPhysicalNumberOfRows行的总数  
                for (int j = 1; j < hssfsheet.getPhysicalNumberOfRows(); j++) {  
                 hssfrow = hssfsheet.getRow(j);  
                 //判断是否还存在需要导入的数据  
                    if (hssfrow == null) {  
                     System.out.println("这里已没有数据,在第"+i+"列,第"+j+"行");  
                     break;  
                    }  
                    /** *//**将EXCEL中的第 j 行,第一列的值插入到实例中*/ 
                    if (hssfrow.getCell((short) 0) == null) {  
                     name = "";  
                    } else if (hssfrow.getCell((short) 0).getCellType() == 0) {  
                     name = new Double(hssfrow.getCell((short) 0).getNumericCellValue()).toString();  
                    }  
                    //如果EXCEL表格中的数据类型为字符串型  
                    else {  
                     name = hssfrow.getCell((short) 0).getStringCellValue().trim();  
                    }  
                    /** *//**将EXCEL中的第 j 行,第二列的值插入到实例中*/ 
                    //姓名  
                    if(hssfrow.getCell((short) 1) == null){  
                     sex = "";  
                    } else if(hssfrow.getCell((short) 1).getCellType() == 0) {  
                        sex = new Double(hssfrow.getCell((short) 1).getNumericCellValue()).toString();  
                    }  
                    //如果EXCEL表格中的数据类型为字符串型  
                    else {  
                        sex = hssfrow.getCell((short) 1).getStringCellValue().trim();  
                    }  
                    /** *//**将EXCEL中的第 j 行,第三列的值插入到实例中*/ 
                    //姓名  
                    if(hssfrow.getCell((short) 1) == null){  
                     age = "";  
                    } else if(hssfrow.getCell((short) 1).getCellType() == 0) {  
                        age = new Double(hssfrow.getCell((short) 1).getNumericCellValue()).toString();  
                    }  
                    //如果EXCEL表格中的数据类型为字符串型  
                    else {  
                        age = hssfrow.getCell((short) 1).getStringCellValue().trim();  
                    }  
                      
                    name = name.trim();  
                    sex = sex.toUpperCase();  
                      
                    if (name.equals("")) {  
                     error.setName(name);  
                     error.setMessage("姓名不能为空");  
                       
                     list.add(error);  
                     continue;  
                    } else {  
                     fm.setName(name);  
                     fm.setSex(sex);  
                     fm.setAge(age);  
                       
                     session.save(fm);  
                    }  
                    //导入成功加1  
                    input++;  
                }  
            }  
              
            session.saveObjs(list.toArray());  
        } catch () {  
           
        }  
}  


import java.io.*;
import java.sql.*;
import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.*;
import org.apache.struts.action.*;
import org.apache.struts.upload.FormFile;
import org.apache.commons.beanutils.BeanUtils;

public class Action {
/**//*
  * 把数据库中的字段导入到Excel ,并生成Excel文档
  **/
public ActionForward getDownload(ActionMapping actionMapping,
   ActionForm actionForm, HttpServletRequest request,
   HttpServletResponse response) throws Exception {
  Form fm = (Form) actionForm;
  // Excel 文件存放在服务器的相对路径下
  String outputFile = request.getRealPath("/tmp/Excel.xls");
 
  try {
   // 创建新的Excel 工作簿
   HSSFWorkbook workbook = new HSSFWorkbook();
   // 在Excel 工作簿中建一工作表
   HSSFSheet sheet = workbook.createSheet("Sheet1");
   // 设置单元格格式(文本)
   HSSFCellStyle cellStyle = workbook.createCellStyle();
   cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("@"));
  
   // 在索引0的位置创建行(第一行)
   HSSFRow row = sheet.createRow((short) 0);
  
   HSSFCell cell1 = row.createCell((short) 0);// 第一列
   HSSFCell cell2 = row.createCell((short) 1);
   HSSFCell cell3 = row.createCell((short) 2);
   // 定义单元格为字符串类型
   cell1.setCellType(HSSFCell.CELL_TYPE_STRING);
   cell2.setCellType(HSSFCell.CELL_TYPE_STRING);
   cell3.setCellType(HSSFCell.CELL_TYPE_STRING);
  
   cell1.setEncoding(HSSFCell.ENCODING_UTF_16);
   cell2.setEncoding(HSSFCell.ENCODING_UTF_16);
   cell3.setEncoding(HSSFCell.ENCODING_UTF_16);
   // 在单元格中输入数据
   cell1.setCellValue("姓名");
   cell2.setCellValue("性别");
   cell3.setCellValue("年龄");
  
   Connection connection = session.connection();
  
   String sql = "Select t.name, t.sex, t.age from table t where t.sex = ?";
  
   try {
    PreparedStatement ps = connection.prepareStatement(sql);
    ps.setString(1, fm.getSex());// 传入查询条件
    ResultSet rs = ps.executeQuery();// 查询结果存入rs
    connection.commit();// 执行SQL
   
    while (rs.next()) {
    //设置j行从第二行开始
     int j = 1;
     row = sheet.createRow((short) j);
     //设置i列从第二列开始
     for (int i = 1; i <= 3; i++) {
      HSSFCell cell = row.createCell((short) (i-1));
      // 设置单元格格式
      cell.setCellStyle(cellStyle);
      cell.setCellType(HSSFCell.CELL_TYPE_STRING);
      cell.setEncoding(HSSFCell.ENCODING_UTF_16);
      cell.setCellValue(rs.getString(i));
     }
    
     j++;
    }
   
    request.setAttribute("message", "文件生成成功!");
   } catch (SQLException e) {
    request.setAttribute("message", "创建文件失败!");
    e.printStackTrace();
   }
   // 删除路径下同名的Excel 文件
   File path = new File(outputFile);
   path.delete();
  
   // 新建一输出文件流
   FileOutputStream fOut = new FileOutputStream(outputFile);
   // 把相应的Excel 工作簿存盘
   workbook.write(fOut);
   // 操作结束,关闭文件
   fOut.flush();
   fOut.close();
    //该处如果Excel过大会影响效率,谁有好的想法可以提出来参考(不过从页面下载完后就会清空)
   request.getSession().setAttribute("Download", outputFile);
  
  } catch (Exception ioexception) {
   request.setAttribute("message", "创建文件失败!");
   return actionMapping.findForward("outJSP");
  }
 
  return actionMapping.findForward("outJSP");
}

/**//*
  * 从Excel文件中读取数据,并导入到数据库中
  **/
  public ActionForward getUpload(ActionMapping actionMapping,
   ActionForm actionForm, HttpServletRequest request,
   HttpServletResponse response) throws Exception {
  // 获取excel 文件
  Form fm = (Form) actionForm;
  FormFile formfile = fm.getUploadfile();
  InputStream inputstream = formfile.getInputStream();
  fm.clear();// 清空
  Session session = HibernateSession.currentSession();
  ArrayList list = new ArrayList();
  int input = 0; //导入记数
  String name = null;
  String sex = null;
  String age = null;
 
  try {
   //通过得到的文件输入流inputstream创建一个HSSFWordbook对象
         HSSFWorkbook hssfworkbook = new HSSFWorkbook(inputstream);
         HSSFSheet hssfsheet = hssfworkbook.getSheetAt(0);//第一个工作表
   HSSFRow hssfrow = hssfsheet.getRow(0);//第一行
  
   //遍历该表格中所有的工作表,i表示工作表的数量 getNumberOfSheets表示工作表的总数
            for (int i = 0; i < hssfworkbook.getNumberOfSheets(); i++) {
             hssfsheet = hssfworkbook.getSheetAt(i);
            
             //遍历该行所有的行,j表示行数 getPhysicalNumberOfRows行的总数
                for (int j = 1; j < hssfsheet.getPhysicalNumberOfRows(); j++) {
                 hssfrow = hssfsheet.getRow(j);
                 //判断是否还存在需要导入的数据
                    if (hssfrow == null) {
                     System.out.println("这里已没有数据,在第"+i+"列,第"+j+"行");
                     break;
                    }
                    /** *//**将EXCEL中的第 j 行,第一列的值插入到实例中*/
                    if (hssfrow.getCell((short) 0) == null) {
                     name = "";
                    } else if (hssfrow.getCell((short) 0).getCellType() == 0) {
                     name = new Double(hssfrow.getCell((short) 0).getNumericCellValue()).toString();
                    }
                    //如果EXCEL表格中的数据类型为字符串型
                    else {
                     name = hssfrow.getCell((short) 0).getStringCellValue().trim();
                    }
                    /** *//**将EXCEL中的第 j 行,第二列的值插入到实例中*/
                    //姓名
                    if(hssfrow.getCell((short) 1) == null){
                     sex = "";
                    } else if(hssfrow.getCell((short) 1).getCellType() == 0) {
                        sex = new Double(hssfrow.getCell((short) 1).getNumericCellValue()).toString();
                    }
                    //如果EXCEL表格中的数据类型为字符串型
                    else {
                        sex = hssfrow.getCell((short) 1).getStringCellValue().trim();
                    }
                    /** *//**将EXCEL中的第 j 行,第三列的值插入到实例中*/
                    //姓名
                    if(hssfrow.getCell((short) 1) == null){
                     age = "";
                    } else if(hssfrow.getCell((short) 1).getCellType() == 0) {
                        age = new Double(hssfrow.getCell((short) 1).getNumericCellValue()).toString();
                    }
                    //如果EXCEL表格中的数据类型为字符串型
                    else {
                        age = hssfrow.getCell((short) 1).getStringCellValue().trim();
                    }
                   
                    name = name.trim();
                    sex = sex.toUpperCase();
                   
                    if (name.equals("")) {
                     error.setName(name);
                     error.setMessage("姓名不能为空");
                    
                     list.add(error);
                     continue;
                    } else {
                     fm.setName(name);
                     fm.setSex(sex);
                     fm.setAge(age);
                    
                     session.save(fm);
                    }
                    //导入成功加1
                    input++;
                }
            }
           
            session.saveObjs(list.toArray());
        } catch () {
        
        }
}
}


2.Form的写法

Java代码
import org.apache.struts.action.ActionForm;  
import org.apache.struts.upload.FormFile;  
 
public class Form extends ActionForm {  
// 上传的文件  
private FormFile _flddo;  
   
public void setUploadfile(FormFile formfile) {  
  _flddo = formfile;  
}  
   
public FormFile getUploadfile() {  
  return _flddo;  
}  
   
public void clear() {  
  _flddo = null;  
}  


import org.apache.struts.action.ActionForm;
import org.apache.struts.upload.FormFile;

public class Form extends ActionForm {
// 上传的文件
private FormFile _flddo;

public void setUploadfile(FormFile formfile) {
  _flddo = formfile;
}

public FormFile getUploadfile() {
  return _flddo;
}

public void clear() {
  _flddo = null;
}
}



3.上传页面Upload.jsp

Java代码
<%@ page contentType="text/html; charset=GBK" language="java"%>  
<%@ taglib uri="http://jakarta.apache.org/struts/tags-html" prefix="html"%>  
 
<html>  
<html:form action="/Action.do?method=getUpload" method="POST" enctype="multipart/form-data">  
  <html:file property="uploadfile" size="80%" />  
  <input type="button" value="导 入" onclick="upload(this.form)" class="buttonGray">  
</html:form>  
</html>  
 
<script language="javascript">  
function upload(obj)  
{  
if(confirm("您现在选择的是XXX,您确定要导入吗?"))  
{  
  var uploadfile = document.all.uploadfile.value;  
  if((null == uploadfile) ||( "" == uploadfile))  
  {  
   alert("上传文件没有指定!");  
   return false;  
  }  
     obj.action = '<html:rewrite page="/Action.do?method=getUpload"/>';  
     obj.submit();  
}  
}  
</script> 

<%@ page contentType="text/html; charset=GBK" language="java"%>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-html" prefix="html"%>

<html>
<html:form action="/Action.do?method=getUpload" method="POST" enctype="multipart/form-data">
  <html:file property="uploadfile" size="80%" />
  <input type="button" value="导 入" onclick="upload(this.form)" class="buttonGray">
</html:form>
</html>

<script language="javascript">
function upload(obj)
{
if(confirm("您现在选择的是XXX,您确定要导入吗?"))
{
  var uploadfile = document.all.uploadfile.value;
  if((null == uploadfile) ||( "" == uploadfile))
  {
   alert("上传文件没有指定!");
   return false;
  }
     obj.action = '<html:rewrite page="/Action.do?method=getUpload"/>';
     obj.submit();
}
}
</script>

4.下载页面Download.jsp

Java代码
<%@ page contentType="text/html; charset=GBK"%>  
<%@ taglib uri="http://jakarta.apache.org/struts/tags-html" prefix="html" %>  
<%@ taglib uri="http://jakarta.apache.org/struts/tags-bean" prefix="bean" %>  
 
<%  
//获取下载文件  
String download = (String) request.getSession().getAttribute("Download");  
//清空文件  
request.getSession().removeAttribute("Download");  
%>  
 
<html>  
下传文件 <a href="<%=download %>" name="下载">下载</a>  
</html> 
分享到:
评论

相关推荐

    POI导入导出EXCEL文件.(struts 1.x and struts2.x).doc

    ### POI导入导出EXCEL文件在Struts框架中的应用 #### 一、概述 本文档将详细介绍如何在Web应用程序中使用Apache POI库来实现Excel文件的导入与导出功能,具体而言,我们将聚焦于Struts 1.x版本的应用案例,同时也...

    POI导入导出excel

    描述中提到的"poi导入导出excel文件,项目绝对可以运行,只要将项目导入myeclipse中直接在浏览器中输入http://localhost:8080/strutspoi即可运行",意味着这是一个基于Struts的Web应用程序,它已经集成了Apache POI...

    Struts2 poi动态导入导出Excel源码示例

    首先,让我们深入理解一下如何使用Struts2和POI来实现Excel的导入导出。 1. **Struts2的Action配置**: 在Struts2中,你需要创建一个Action类来处理用户请求。这个Action类会有一个方法,专门处理导入或导出Excel...

    ssh整合poi导入导出Excel

    在Excel导入导出过程中,Apache POI库起到了核心作用。POI提供了HSSF(Horrible Spreadsheet Format)和XSSF(XML Spreadsheet Format)API,分别用于读写旧版的Excel 97-2003格式(.xls)和较新的Excel 2007及以上...

    poi导入导出excel

    下面将详细解释如何使用 POI 实现 Excel 的导入导出功能。 首先,为了导出 Excel,我们需要创建一个 `HSSFWorkbook` 对象,这是 POI 中表示 Excel 工作簿的类。然后,我们可以创建一个或多个 `HSSFSheet` 对象来...

    Poi动态导入导出Excel基于Struts2 Hibernate Spring源码工程实例

    1.本动态导入导出Excel工程导入Eclipse即可用行,支持所有版本的Excel导入导出。 2.程序使用Struts2+POI+SQLSever(SSH即Struts2+Hibernate+Spring)实现Excel动态数据导入和导出,压缩包内含程序源码文件。

    Struts2 Excel导入导出数据

    在处理数据导入导出方面,Struts2提供了强大的支持,特别是与Excel文件的交互。本教程将深入探讨如何利用Struts2实现从Oracle数据库导出数据到Excel,以及如何将Excel文件中的数据导入到Oracle。 首先,我们需要...

    使用poi从数据库导出excel表的示例

    总结起来,"使用poi从数据库导出excel表的示例"是一个结合了Struts1 MVC框架和Apache POI库的Java编程任务,它涉及数据库连接、SQL查询、Excel文件生成以及Web应用响应。这个过程不仅有助于数据的高效管理和分享,也...

    struts2 poi 导入xls xlsx 绝对兼容

    以上就是关于"Struts2 poi 导入xls xlsx 绝对兼容"的相关知识点,通过Struts2和Apache POI的结合,开发者可以轻松地在Java Web应用中处理Excel文件,实现数据的导入和导出功能,提高工作效率。在实际项目中,可以...

    struts2Ecxel导入导出

    Struts2是一个非常流行的Java Web框架...总结,Struts2结合Apache POI库可以轻松实现Excel的导入导出功能,极大地增强了Web应用的数据交互能力。理解并掌握这些知识点,对于开发高效、用户友好的数据处理功能至关重要。

    struts2+poi实现导出Excel文件.pdf

    在Struts2框架中,导出Excel功能主要通过一个Action类实现。Action类是Struts2的核心组件,负责处理用户的请求并执行相应的业务逻辑。在本例中,创建了一个名为`panyu.flow.web.action.ExcelAction`的Action类,这个...

    java实现Excel导入导出

    Java 实现 Excel 导入导出 ...在 Struts2+Spring 框架中实现 Excel 导入导出需要使用 POI 库来读取和写入 Excel 文件中的数据,并对数据进行处理。使用 POI 库可以简化 Excel 文件的操作,并提高程序的性能。

    java实现导入导出Excel表

    在Java编程领域,导入和导出Excel表格是一项常见的任务,特别是在数据处理、报表生成和数据分析等场景中。...通过深入研究和实践,开发者可以掌握Java环境下Excel的导入导出技术,同时提升对SSH框架的运用能力。

    poi 导出EXCEL 例子

    本例子将详细介绍如何使用Apache POI库导出Excel文件。 首先,我们需要添加Apache POI库到我们的项目中。在给定的文件列表中,我们看到`poi-2.5.1.jar`,这是Apache POI的一个早期版本。现代项目通常会使用更新的...

    struts2+poi实现excel文件的导出

    Struts2 和 Apache POI 的整合允许开发者轻松地实现在 Web 应用程序中导出 Excel 文件的功能。Apache POI 是一个 Java 库,它提供了处理 Microsoft Office 格式(如 .xls 和 .xlsx)的能力,包括创建、读取和修改 ...

    ssh 导入导出excel+百度富文本编辑器+highcharts

    标题中的“ssh 导入导出excel”涉及到SSH框架中处理Excel数据的能力。在实际项目中,我们经常需要从Excel文件中读取数据或者将数据导出到Excel文件,以便于数据交换和报表生成。在SSH框架下,可以使用Apache POI库来...

    Struts2数据库数据导入导出

    运用struts2将数据库中的数据导入和导出,同时会用到poi的jar包

    POI web导入导出类封装!

    poi即Excel导入导出,在开发过程中了,为了提高数据录入速度, 一些系统都会使用导入功能,导入目前只能通过流的方式读写,那么为了此操作的便利性,提供此工具类,是原有的excel数据读取到泛型集合中,然后再对集合...

    struts2数据导入导出

    Struts2框架结合Apache POI库可以轻松实现Excel文件的数据导入导出功能。本文档将详细介绍如何使用Struts2与POI进行数据的导入导出。 #### 二、Struts2简介 Struts2是一个开源的Web应用框架,基于Java平台。它采用...

    ssh整合web导出excel案例

    在本文中,我们将探讨如何在SSH(Spring、Struts2、Hibernate)框架下整合实现Web应用导出Excel文件的功能。SSH是一个广泛使用的Java Web开发框架,它提供了强大的数据持久层、MVC架构以及依赖注入等功能。在这个...

Global site tag (gtag.js) - Google Analytics