我做的项目中有些JSP数据表单生成后,想将其页面显示的内容导到Excel或TXT中去。该怎么做啊???有代码的发点参考一下。谢谢啊在线等啊

解决方案 »

  1.   

    可以试试
    http://dev.csdn.net/article/34/34334.shtm
      

  2.   

    <%String CONTENT_TYPE = "";
    CONTENT_TYPE = "application/msexcel; charset=BIG5";
    response.setContentType(CONTENT_TYPE);
    response.setHeader("Content-disposition", "attachment; filename=xxx.xsl");
    %>
    在JSP文件裡加上這幾句就可以
      

  3.   

    实现你所要功能的核心代码如下:
                    
    WritableWorkbook workbook = null;
    WritableSheet sheet = null;
    Label label = null; try {
    workbook = Workbook.createWorkbook(os);
    sheet = workbook.createSheet("First Sheet", 0); ResultSetMetaData rsmd = rs.getMetaData();
    int columnCount = rsmd.getColumnCount();
    String colName = null;
    int row = 0;
    for (int i = 0; i < columnCount; i++) {
    colName = rsmd.getColumnName(i + 1);
    label = new Label(i, row, colName);
    sheet.addCell(label);
    }
    row++;
    while (rs.next()) {
    for (int i = 0; i < columnCount; i++) {
    label = new Label(i, row, rs.getString(i+1));
    sheet.addCell(label);
    }
    row++;
    }
    // 关闭文件
    workbook.write();
    workbook.close();
    } catch (SQLException e) {
                            e.getMessage()
                    }
      

  4.   

    javascript代码,你试试
    <!--
    function toExcel(){
    try{
    var oXL = new ActiveXObject("Excel.Application");
    var oWB = oXL.Workbooks.Add();
    var oSheet = oWB.ActiveSheet;
    }catch(e){
    alert("创建excel对象失败,请确认已经安装了excel软件!");
    return false;
    }
    var a = document.all.total;//total为表的id,自己指定的。
    var Lenr1 = a.rows.length;
    for (i=0;i<Lenr1;i++) { 
    var Lenc1 = a.rows(i).cells.length; 
    for (j=0;j<Lenc1;j++) { 
    oSheet.Cells(i+1,j+1).value = a.rows(i).cells(j).innerText; 


    if(document.all.mytable!=undefined){
    var b = document.all.mytable;
    var Lenr2 = b.rows.length;
    for (i=0;i<Lenr2;i++) { 
    var Lenc2 = b.rows(i).cells.length; 
    for (j=0;j<Lenc2;j++) { 
    oSheet.Cells(i+4,j+1).value = b.rows(i).cells(j).innerText; 


    }
    oXL.Visible = true;
    CollectGarbage();
    }
    //-->
      

  5.   

    类似于下面这样:<%@page contentType="application/vnd.ms-excel" %>
    <%response.setHeader("Content-Disposition","attachment;filename=myExcel.xls");%> 
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    <%@ page import="java.util.*" %><%
    HashMap map = new HashMap();
    map.put("1","d");
    map.put("2","f");
    map.put("3","e");
    request.setAttribute("map",map);
    %>
    <table>
      <c:forEach items="${map}" var="i">
        <tr>
          <td>${i.key}</td>
          <td>${i.value}</td>
        </tr>
      </c:forEach>
    </table>
      

  6.   

    我把这段代码直接放在JSP  JS里面了,可是总是执行:创建excel对象失败,请确认已经安装了excel软件 这句话。我是安装了EXCEL软件的。怎么回事呢??再解释一下吧
      

  7.   

    他是用的一个插件, 叫做jxl.jar,你可以到网上下载也可以用poi,功能应该更强大
      

  8.   

    poi 相应资源网上很多的一看就能用了.
      

  9.   

    我那里有一个可以直接把没有嵌套的<Table></table> 导出为真正的Excel. 不过需要认证的会员
    http://www.java2000.net/viewthread.jsp?tid=1977使用了 jxl
      

  10.   

    public class EvaluateLogExport implements Controller {
    private static final Log log = LogFactory.getLog(EvaluateLogExport.class); public ModelAndView handleRequest(HttpServletRequest request,
    HttpServletResponse response) throws Exception {
    // 读取数据
    HttpSession session = request.getSession();
    List list = (List) session.getAttribute("companyDept"); // 定义表头
    String[] columnTitles = { "部门名称", "知识考评", "行为事件", "主管评定", "否定行为",
    "活动记录", "建议方案", "宣传报道", "经典推荐", "证书类", "奖励表彰", "心理测验" };
    try { //字符串转换为时间
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    String time = format.format((new Date())); response.setHeader("Content-disposition",
    "attachment; filename=EvaluateLog-" + time + ".xls");
    response.setContentType("application/msexcel");
    OutputStream outputStream; outputStream = response.getOutputStream();
    WritableWorkbook workbook = ExcelExportUtil.doExport("EvaluateLog",
    columnTitles, list, outputStream);
    ExcelExportUtil.flushExcel(workbook, outputStream, true); } catch (Exception e) {
    log.error(e);
    PutMessage meg = new PutMessage(request);
    meg.PutError(e.getMessage()); }
    return null;
    }}
      

  11.   

    哥们 我最近刚做完 excel 的导入 导出,
    主要是这两个类 ,  你再仔细研究一下
    我把有些代码 写死了 你看着改改最好自己再参照 JXL API (专门操作excel的 百度一下)
    如果找不到 api 的话  我的msn : [email protected]
    我给你 
    package com.guanchen.Excel;
    import hib.obj.TblAddressListUser;
    import hib.obj.TblAddressListUserDAO;
    import jxl.*;
    import jxl.write.*;
    import java.io.*;
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Map;
    import java.util.Set;import org.springframework.context.support.ClassPathXmlApplicationContext;
    public class ExcelHandle{
    /**
     * @param filePath Excel文档的路径
     * @param line  Excel文档中从第几(line)行开始为有效数据?
     * @param map  在excel中每一column对应的TblAddressListUser的什么属性  Key为属性 Value为对应的列值(从0开始)
     * @return excel中所有的有效数据 封装成 TblAddressListUser 对象保存到list
     */
        public static List readExcel(String filePath,String line,Map map)
        {
         if("".equals(line) || line==null){
         line="1";
         }
         List<TblAddressListUser> list = new ArrayList();
            try
            {
                InputStream is = new FileInputStream(filePath);
                Workbook rwb = Workbook.getWorkbook(is);
                //Sheet st = rwb.getSheet("0")这里有两种方法获取sheet表,1为名字,而为下标,从0开始
                Sheet st = rwb.getSheet(0);
                int rows=st.getRows();
                int columns=st.getColumns();
                String[][] result=new String[rows][columns];
                
                for(int i=Integer.parseInt(line)-1;i<rows;i++){
                 TblAddressListUser user=new TblAddressListUser();
                 boolean isUsed=true;
                 b:for (int j = 0; j < columns; j++) {
                 if(Integer.parseInt((String) map.get("userName"))==j){
                 String name=st.getCell(j, i).getContents();
                 if("".equals(name)||name==null){
                 isUsed=false;
                 break b;
                 }else{
    //             System.out.println("userName="+ st.getCell(j, i).getContents());
                     user.setUserName(name);
                 }
                 }
                 if(Integer.parseInt((String) map.get("mobile"))==j){
                 String mobile=st.getCell(j, i).getContents();
                 if("".equals(mobile)||mobile==null){
                 isUsed=false;
                 break b;
                 }else{
                 try {
    Long.parseLong(mobile.trim());
    } catch (RuntimeException e) {
    isUsed=false;
    break b;
    }
    //             System.out.println("mobile="+ st.getCell(j, i).getContents());
                     user.setMobile(mobile);
                 }
                 }
                 if(Integer.parseInt((String) map.get("sex"))==j){
    //             System.out.println("sex="+ st.getCell(j, i).getContents());
                 String sex=st.getCell(j, i).getContents();
                 if("男".equals(sex)){
                 user.setSex("1");
                 }else{
                 user.setSex("0");
                 }
                 }
                 if(Integer.parseInt((String) map.get("tel"))==j){
    //             System.out.println("tel="+ st.getCell(j, i).getContents());
                 user.setTel(st.getCell(j, i).getContents());
                 }
                 if(Integer.parseInt((String) map.get("email"))==j){
    //             System.out.println("email="+ st.getCell(j, i).getContents());
                 user.setEmail(st.getCell(j, i).getContents());
                 }
                 if(Integer.parseInt((String) map.get("corp"))==j){
    //             System.out.println("corp="+ st.getCell(j, i).getContents());
                 user.setCorp(st.getCell(j, i).getContents());
                 }
                 if(Integer.parseInt((String) map.get("card_id"))==j){
    //             System.out.println("card_id="+ st.getCell(j, i).getContents());
                 user.setCardId(st.getCell(j, i).getContents());
                 }
                 if(Integer.parseInt((String) map.get("userDesc"))==j){
    //             System.out.println("userDesc="+ st.getCell(j, i).getContents());
                 user.setUserDesc(st.getCell(j, i).getContents());
                 }
    }
                 if(isUsed){
                 list.add(user);
                 }
                }
    //            for(int n=0;n<rows;n++){
    //             for(int m=0;m<columns;m++){
    //             System.out.print(result[n][m]+"  ---");
    //             }
    //             System.out.println();
    //            }
                rwb.close();
            }
            catch(Exception e)
            {
             return null;
            }
    return list;
        }    /**
         * 
         * @param os  输入流
         * @param users  数据库中用户的信息
         * @return true 文件创建成功  false 文件创建失败
         */
        public static boolean writeExcel(Set users,String filePath)
        {
            try
            {
                /** *//**
                 * 只能通过API提供的工厂方法来创建Workbook,而不能使用WritableWorkbook的构造函数,
                 * 因为类WritableWorkbook的构造函数为protected类型
                 * method(1)直接从目标文件中读取WritableWorkbook wwb = Workbook.createWorkbook(new File(targetfile));
                 * method(2)如下实例所示 将WritableWorkbook直接写入到输出流
                 */
             File os=new File(filePath);
                WritableWorkbook wwb = Workbook.createWorkbook(os);
                //创建Excel工作表 指定名称和位置
                WritableSheet ws = wwb.createSheet("通讯录",0);
                ws.setColumnView(0, 10);
                ws.setColumnView(1, 20);
                ws.setColumnView(2, 6);
                ws.setColumnView(3, 20);
                ws.setColumnView(4, 22);
                ws.setColumnView(5, 30);
                ws.setColumnView(6, 22);
                ws.setColumnView(7, 18);
                ws.setColumnView(8, 40);
                //**************往工作表中添加数据*****************            //1.添加Label对象
                
                WritableFont wftitle = new WritableFont(WritableFont.ARIAL,12,WritableFont.BOLD,false);
                WritableCellFormat wfTitle=new WritableCellFormat(wftitle);
                Label label = new Label(0,0,"  ",wfTitle);
                ws.addCell(label);
                WritableFont wftitle1 = new WritableFont(WritableFont.TAHOMA,10,WritableFont.NO_BOLD,false);
                WritableCellFormat wfTitle1=new WritableCellFormat(wftitle1);
                wfTitle1.setLocked(false);
                wfTitle1.setShrinkToFit(true);
                wfTitle1.setVerticalAlignment(VerticalAlignment.CENTRE);
                wfTitle1.setAlignment(Alignment.CENTRE);
                wfTitle1.setBackground(Colour.GREY_25_PERCENT);
                wfTitle1.setBorder(Border.ALL, BorderLineStyle.THIN);
                Label label1 = new Label(0,1,"姓名",wfTitle1);
                ws.addCell(label1);
                WritableFont wftitle2 = new WritableFont(WritableFont.TAHOMA,10,WritableFont.NO_BOLD,false);
                WritableCellFormat wfTitle2=new WritableCellFormat(wftitle2);
                wfTitle2.setLocked(false);
                wfTitle2.setShrinkToFit(true);
                wfTitle2.setVerticalAlignment(VerticalAlignment.CENTRE);
                wfTitle2.setAlignment(Alignment.CENTRE);
                wfTitle2.setBackground(Colour.GREY_25_PERCENT);
                wfTitle2.setBorder(Border.ALL, BorderLineStyle.THIN);
                Label label2 = new Label(1,1,"手机号码",wfTitle2);
                ws.addCell(label2);
      

  12.   

    package com.guanchen.Excel;import java.io.File;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Map;import javax.servlet.http.HttpServletRequest;import org.apache.commons.fileupload.FileItem;
    import org.apache.commons.fileupload.FileItemFactory;
    import org.apache.commons.fileupload.disk.DiskFileItemFactory;
    import org.apache.commons.fileupload.servlet.ServletFileUpload;public class upFile {
    //普通表单的键值对
    private Map fields;
    public Map getFields() {
    return fields;
    }
    public void setFields(Map fields) {
    this.fields = fields;
    }
    public String upFileSys(HttpServletRequest request){
    // 文件上传部分
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    String path="";
    if (isMultipart) {
    try {
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    // 得到所有的表单域,它们目前都被当作FileItem
    List<FileItem> fileItems = upload.parseRequest(request);
    Iterator<FileItem> iter = fileItems.iterator();
    // 依次处理每个表单域

    Map<String, String> map = new HashMap();
    while (iter.hasNext()) {
    FileItem item = (FileItem) iter.next();
    if(item.isFormField()){
    // 如果item是正常的表单域
    String name = item.getFieldName();
        String value = item.getString();
        map.put(name, value);
    }else{
    // 如果item是文件上传表单域
    // 获得文件名及路径
    String fileName = item.getName();
    if (fileName != null) {
    String diskPath=request.getRealPath("TongXunLu/tmp/Address_gc_zht.xls");
    String filePath=diskPath;
    File fullFile = new File(filePath);
    // 如果文件存在则上传
    // if(fullFile.exists()){
    item.write(fullFile);
    path="TongXunLu/tmp/Address_gc_zht.xls";
    // }
    }
    }
    }
    this.setFields(map);
    } catch (Exception e) {
    e.printStackTrace();
    return null;
    }
    } else {
    System.out.println("the enctype must be multipart/form-data");
    return null;
    }
    return path;
    }
    }
      

  13.   

    非常的感谢你哦~~~~~VERY GOOD.....