请问用java怎么样实现导出excel表,并且点击导出的时候要先弹出导出路径。谢谢,有没有完整的代码

解决方案 »

  1.   

    可以参考这个实例:
    JXL导出Excel数据表
      

  2.   

    前天有个问类似问题的lz,你可以在csdn里搜索你的问题
      

  3.   

    java导出Excel java 代码 /* * Generated by MyEclipse Struts * Template path: templates/java/JavaClass.vtl */ package com.axon.fable.sams.view.action; import java.io.IOException; import java.io.OutputStream; import java.util.List; import javax.serv ... 
    java导出Excel例举方式 
    方法一:导出Excel数据的插件jexcelapi 程序实例如下: 
    public void exportClassroom(OutputStream os) throws PaikeException { try { 
    WritableWorkbook wbook = Workbook.createWorkbook(os); //建立excel文件 
    WritableSheet wsheet = wbook.createSheet("教室信息表", 0); //工作表名称 
    //设置Excel字体 
    WritableFont wfont = new WritableFont(WritableFont.ARIAL, 16, 
    WritableFont.BOLD, false, 
    jxl.format.UnderlineStyle.NO_UNDERLINE, 
    jxl.format.Colour.BLACK); 
    WritableCellFormat titleFormat = new WritableCellFormat(wfont); 
    String[] title = { "教室名", "容 量", "类 型", "其他说明" }; 
    //设置Excel表头 
    for (int i = 0; i < title.length; i++) { 
    Label excelTitle = new Label(i, 0, title[i], titleFormat); 
    wsheet.addCell(excelTitle); 

    int c = 1; //用于循环时Excel的行号 
    ClassroomService cs = new ClassroomService(); 
    List list = cs.findAllClassroom(); //这个是从数据库中取得要导出的数据 
    Iterator it = list.iterator(); 
    while (it.hasNext()) { 
    ClassroomDTO crdto = (ClassroomDTO) it.next(); 
    Label content1 = new Label(0, c, crdto.getRoomname()); 
    Label content2 = new Label(1, c, crdto.getCapicity().toString()); 
    Label content3 = new Label(2, c, crdto.getRoomTypeId() 
    .toString()); 
    Label content4 = new Label(3, c, crdto.getRe()); 
    wsheet.addCell(content1); 
    wsheet.addCell(content2); 
    wsheet.addCell(content3); 
    wsheet.addCell(content4); 
    c++; 
    } wbook.write(); //写入文件 
    wbook.close(); 
    os.close(); 
    } catch (Exception e) { throw new PaikeException("导出文件出错"); } } 
      

  4.   

    方法二:直接用Java代码实现导出Excel报表 /* * Generated by MyEclipse Struts * Template path: templates/java/JavaClass.vtl */ package com.axon.fable.sams.view.action; import java.io.IOException; import java.io.OutputStream; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import jxl.Workbook; import jxl.write.WriteException; import jxl.write.biff.RowsExceededException; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; import com.axon.fable.empolderpackage.out.OutJavaScript; import com.axon.fable.empolderpackage.page.Pager; import com.axon.fable.empolderpackage.string.MyPublic; import com.axon.fable.sams.common.BaseAction; import com.axon.fable.sams.exception.AppBusinessException; import com.axon.fable.sams.exception.AppSystemException; /** * MyEclipse Struts * Creation date: 06-28-2007 * * XDoclet definition: * @struts.action path="/axon" name="axonForm" input="/samspage/zm/axon.jsp" parameter="method" scope="request" validate="true" * @struts.action-forward name="success" path="/samspage/zm/content.jsp" */ public class StshipoperationAction extends BaseAction { /* * Generated Methods */ private static Session session=null; private static Transaction ts=null; private static Query queryC=null; private static Query queryR=null; private static Query query=null; private static List list=null; private static Integer startRow; private static Integer ncurrentPage; private static Integer cell; private static String property; private static String sql; private static String type; private static String condition ;//是否导出当前页 private static String currentPage; private static String from ; private static String pactdata; private static String voyagename; private static String voyageno; private static String dwt ; private static String hirefrom ; private static String deliveryposion ; private static String redeliveryposion ; private static String sheepowner ; private static String addr; private static String addcomm; private static String rent; private static String fileName ; private static OutputStream os; @Override public ActionForward findAll(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { // TODO Auto-generated method stub return null; } @Override public ActionForward findById(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { // TODO Auto-generated method stub return null; } @Override public ActionForward save(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { // TODO Auto-generated method stub return null; } public static String strNull(Object nullStr,String newStr,Integer cell){ if(nullStr==null||nullStr.equals("")){return newStr;}else{cell+=1;return nullStr+"";} } public static String getStr(String str,Integer cell){ if(str==null||str.trim().equals("")){return "";}else{cell+=1;return ","+str;} } public static String getExcelTile(String title){ if(title==null) return ""; if(title.equals("modela.stsid")) return "编号"; if(title.equals("modelc.pactdata")) return "合同日期"; if(title.equals("modela.voyagename")) return "航名"; if(title.equals("modela.voyageno")) return "航次"; if(title.equals("modelc.dwt")) return "DWT"; if(title.equals("modelc.hirefrom")) return "受载期"; if(title.equals("modela.deliveryposion")) return "交船地点"; if(title.equals("modela.redeliveryposion")) return "还船地点"; if(title.equals("modelc.sheepowner")) return "联系人"; if(title.equals("modelc.addr")) return "经纪人拥金"; if(title.equals("modelc.addcomm")) return "ADD COMM"; if(title.equals("modelc.rent")) return "租金"; return ""; } public ActionForward exporVoyagesInfoToExcel(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { list=null; startRow=0; ncurrentPage=1; cell=0; type =request.getParameter("type"); condition =request.getParameter("condition");//是否导出当前页 currentPage =request.getParameter("currentPage"); from =request.getParameter("from"); pactdata = request.getParameter("modelc.pactdata"); voyagename = request.getParameter("modela.voyagename"); voyageno = request.getParameter("modela.voyageno"); dwt = request.getParameter("modelc.dwt"); hirefrom = request.getParameter("modelc.hirefrom"); deliveryposion = request.getParameter("modela.deliveryposion"); redeliveryposion = request.getParameter("modela.redeliveryposion"); sheepowner = request.getParameter("modelc.sheepowner"); addr = request.getParameter("modelc.addr"); addcomm = request.getParameter("modelc.addcomm"); rent = request.getParameter("modelc.rent"); if(type!=null&&type.trim().equals("1")){ type ="已还船舶--费用未结清"; }else{ type ="已还船舶--费用已结清"; } property =getStr(pactdata,cell)+getStr(voyagename,cell)+getStr(voyageno,cell)+getStr(dwt,cell)+getStr(hirefrom,cell) +getStr(deliveryposion,cell)+getStr(redeliveryposion,cell)+getStr(sheepowner,cell)+getStr(addr,cell)+getStr(addcomm,cell) +getStr(rent,cell); property = property.substring(1); String split[] = property.split(","); // System.out.println("-----------------------------property:"+property); if(currentPage!=null&&!currentPage.trim().equals("")){ ncurrentPage =Integer.parseInt(currentPage); }else{ OutJavaScript.outString(response, "Sorry! Failed to get information of pager."); return null; } try { session =getServiceLocator().getBaseHibernateDAO().getSession(); sql ="select count(*) "+from; query =session.createQuery(sql); list = query.list(); for (int i = 0; i < list.size(); i++) { totalSize =(Integer)list.get(i); if(totalSize!=0){ pager =new Pager(ncurrentPage,totalSize); } } query =getServiceLocator().getBaseHibernateDAO().getSession().createQuery("select " +property+from); if(condition!=null&&condition.trim().equals("1")){//分页数据 startRow = (ncurrentPage - 1)*pager.getPageSize(); query.setFirstResult(startRow); query.setMaxResults(pager.getPageSize()); // System.out.println("---------------------------------------------------query:"+query); } list = query.list(); fileName = "shipInfo"; os = response.getOutputStream(); response.reset(); response.setHeader("Content-disposition", "attachment; filename=" +fileName + ".xls"); response.setContentType("application/msexcel"); jxl.write.WritableWorkbook wbook = Workbook.createWorkbook(os); jxl.write.WritableSheet wsheet = wbook.createSheet("the first sheet", 0); for (int i = 0; i < split.length; i++) { jxl.write.Label wlabel0; wlabel0 = new jxl.write.Label(i, 0, getExcelTile(split[i])); wsheet.addCell(wlabel0); } jxl.write.Label wlabel1; for(int i=0;i<list.size();i++) { if(split.length==1){ Object strval = (Object) list.get(i); String javaScript=""+MyPublic.toHtmlStr(strval==null?"":strval.toString().trim())+""; wlabel1 = new jxl.write.Label(0, i+1,strval==null?"":strval.toString().trim() ); wsheet.addCell(wlabel1); }else{ Object[] strval = (Object[]) list.get(i); for(int j=0;j<strval.length;j++) { String javaScript=""+MyPublic.toHtmlStr(strval[j]==null?"":strval[j].toString().trim())+""; //System.out.println("===================script:"+javaScript); wlabel1 = new jxl.write.Label(j, i+1,strval[j]==null?"":strval[j].toString().trim() ); wsheet.addCell(wlabel1); } } } wbook.write(); response.flushBuffer(); wbook.close(); os.close(); } catch (IOException e) { // TODO Auto-generated catch block OutJavaScript.outString(response, "Sorry! Export Excel exception."); e.printStackTrace(); } catch (HibernateException e1) { // TODO Auto-generated catch block OutJavaScript.outString(response, "Sorry! Database exception."); e1.printStackTrace(); } catch (AppSystemException e1) { // TODO Auto-generated catch block OutJavaScript.outString(response, "Sorry! System exception."); e1.printStackTrace(); } catch (AppBusinessException e1) { // TODO Auto-generated catch block OutJavaScript.outString(response, "Sorry! Database exception."); e1.printStackTrace(); } catch (RowsExceededException e) { // TODO Auto-generated catch block OutJavaScript.outString(response, "Sorry! Export Excel exception."); e.printStackTrace(); } catch (WriteException e) { // TODO Auto-generated catch block OutJavaScript.outString(response, "Sorry! Export Excel exception."); e.printStackTrace(); } return null; } @Override public ActionForward update(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { // TODO Auto-generated method stub return null; } }还有其他很多种 字数限制 无法一一举例方式 
      

  5.   

    使用POI。谷歌输入POI 下一个poi的jar包。public class CreateSimpleExcelToDisk { /**
     * @作者:heasen
     * @日期:2010-3-24
     * @功能:手工构建一个简单格式的Excel
     */
    private static List<Student> getStudent() throws Exception{
    List list = new ArrayList();
    SimpleDateFormat df = new SimpleDateFormat("yyyy-mm-dd");

    Student user1 = new Student(1,"张三",16,df.parse("1997-03-12"));
    Student user2 = new Student(2,"李四",17,df.parse("1996-08-12"));
    Student user3 = new Student(3,"王五",26,df.parse("1985-11-12"));
    list.add(user1);
    list.add(user2);
    list.add(user3);

    return list;
    }
    public static void main(String[] args) throws Exception {
    //第一步,创建一个webbook,对应一个Excel文件
    HSSFWorkbook wb = new HSSFWorkbook();
    //第二步,在webbook中添加一个sheet,对应Excel文件中的sheet
    HSSFSheet sheet = wb.createSheet("学生表一");
    //第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
    HSSFRow row = sheet.createRow((int)0);
    //第四步,创建单元格,并设置值表头  设置表头居中
    HSSFCellStyle style = wb.createCellStyle();
    style.setAlignment(HSSFCellStyle.ALIGN_CENTER); //创建一个居中格式

    HSSFCell cell = row.createCell((short)0);
    cell.setCellValue("学号"); cell.setCellStyle(style);
    cell = row.createCell((short)1);
    cell.setCellValue("姓名"); cell.setCellStyle(style);
    cell = row.createCell((short)2);
    cell.setCellValue("年龄"); cell.setCellStyle(style);
    cell = row.createCell((short)3);
    cell.setCellValue("生日"); cell.setCellStyle(style);

    //第五步,写入实体数据 实际应用中这些数据从数据库得到,
    List list = CreateSimpleExcelToDisk.getStudent(); for(int i=0;i<list.size();i++){
    row = sheet.createRow((int)i+1);
    Student stu = (Student) list.get(i);
    //第四步,创建单元格,并设置值
    row.createCell((short)0).setCellValue((double)stu.getId());
    row.createCell((short)1).setCellValue(stu.getName());
    row.createCell((short)2).setCellValue((double)stu.getAge());
    cell = row.createCell((short)3);
    cell.setCellValue(new SimpleDateFormat("yyyy-mm-dd").format(stu.getBirth()));
    }
    //第六步,将文件存到指定位置
    try {
    FileOutputStream fout = new FileOutputStream("E:/students.xls");
    wb.write(fout);
    fout.close();
    } catch (Exception e) {
    e.printStackTrace();
    }
    }
    }
      

  6.   

    导入 jxl.jar
    直接调用下面的方法 import java.io.IOException;
    import java.io.OutputStream;
    import java.sql.*;
    import java.util.List;
    import java.util.Vector;import javax.servlet.http.HttpServletResponse;import jxl.Workbook;
    import jxl.write.Label;
    import jxl.write.WritableSheet;
    import jxl.write.WritableWorkbook;
    import jxl.write.WriteException;
    import jxl.write.biff.RowsExceededException;import com.tybit.entities.Templete;public class DBtoExcel {
    /**
     * 导出Excel表
     * 
     * @param rs
     *            数据库结果集
     * @param filePath
     *            要保存的路径,文件名为 fileName.xls
     * @param sheetName
     *            工作簿名称 工作簿名称,本方法目前只支持导出一个Excel工作簿
     * @param columnName
     *            列名,类型为Vector<STRING></STRING>
     */
    public static void write2Excel(List rs, String fileName,
    HttpServletResponse response) throws SQLException, IOException,
    RowsExceededException, WriteException {
    // 获得导出数据的列数
    String[] title = { "序号", "审核状态", "审核时间", "任务名称", "URL地址", "IP地址", };
    response.setContentType("application/x-msdownload");
    // 定义打印出来后的报表名
    String dispposition = "=?UTF-8?Q?attachment; filename=" + fileName
    + ".xls";
    response.setHeader("Content-Disposition", dispposition);
    OutputStream os = response.getOutputStream();
    WritableWorkbook wwb = Workbook.createWorkbook(os);
    WritableSheet ws = wwb.createSheet(fileName, 0);
    try {
    // 写入列明
    for (int i = 0; i < title.length; i++) {
    Label labelName = new Label(i, 0, title[i]);
    ws.addCell(labelName);
    }
    // 写入数据
    if (rs != null) {
    for (int i = 0; i < rs.size(); i++) {
    Templete tp = (Templete) rs.get(i);
    Label label0 = new Label(0, i + 1, String.valueOf(i + 1));
    String state = "";
    if (tp.getIscheck() == 0) {
    state = "待审核";
    } else {
    state = "已审核";
    }
    Label label1 = new Label(1, i + 1, state);
    Label label2 = new Label(2, i + 1, tp.getCheckdate());
    Label label3 = new Label(3, i + 1, tp.getTaskname());
    Label label4 = new Label(4, i + 1, tp.getUrl());
    Label label5 = new Label(5, i + 1, tp.getIp());
    ws.addCell(label0);
    ws.addCell(label1);
    ws.addCell(label2);
    ws.addCell(label3);
    ws.addCell(label4);
    ws.addCell(label5);
    }
    }
    } catch (Exception ex) {
    ex.printStackTrace();
    } finally {
    // 关闭Excel工作薄对象
    wwb.write();
    wwb.close();
    os.close();
    }
    }
    }
      

  7.   


    导出excel可以用poi这个不错其实更简单的就是在一个jsp中放一个表格table
    然后设置它的头部
    response.setHeader("Content-disposition", "attachment; filename=fileName.xls");
    它就可以导出了
      

  8.   

     // 导出成Excel
    public String exportExcel() { ByteArrayOutputStream out = new ByteArrayOutputStream();
    WritableWorkbook wwb = null; try {
    wwb = Workbook.createWorkbook(out);// 创建workbook
    } catch (Exception e) {
    e.printStackTrace();
    }
    WritableSheet ws = wwb.createSheet("bookInfo", 0);// 创建sheet try { Label l = new Label(0, 0, "书名");
    ws.addCell(l);
    l = new Label(1, 0, "作者");
    ws.addCell(l);
    l = new Label(2, 0, "出版社");
    ws.addCell(l);
    l = new Label(3, 0, "价格");
    ws.addCell(l);
    l = new Label(4, 0, "出版日期");
    ws.addCell(l);
    bookList = bookService.findAll();
    int i = 1;
    for (BookInfo book : bookList) {
    l = new Label(0, i, book.getBookname());
    ws.addCell(l);
    l = new Label(1, i, book.getAuthor());
    ws.addCell(l);
    l = new Label(2, i, book.getPub());
    ws.addCell(l);
    l = new Label(3, i, book.getPrice());
    ws.addCell(l);
    l = new Label(4, i, book.getPubdate());
    ws.addCell(l);
    i++;
    }
    ws.setColumnView(0, 20);// 设置列宽
    ws.setColumnView(1, 20);
    ws.setColumnView(2, 40);
    ws.setColumnView(3, 30);
    ws.setColumnView(4, 30);
    ws.setRowView(0, 500);// 设置行高
    ws.setRowView(1, 500);
    ws.setRowView(2, 500);
    ws.setRowView(3, 500);
    ws.setRowView(4, 500); } catch (RowsExceededException e1) {
    e1.printStackTrace();
    } catch (WriteException e1) {
    e1.printStackTrace();
    } // 输出流
    try {
    wwb.write();
    } catch (IOException ex) { ex.printStackTrace();
    }
    // 关闭流
    try {
    wwb.close();
    } catch (Exception ex) { ex.printStackTrace();
    } // outStream.close();
    os = new ByteArrayInputStream(out.toByteArray());
    return SUCCESS;
    }
      

  9.   


    能告诉我os = new ByteArrayInputStream(out.toByteArray());
    中的OS是OutputStream吗?
      

  10.   

    <a href="http://crabdave.javaeye.com/blog/270235" title="JXL导出Excel数据表" target="_blank">JXL导出Excel数据表</a>