前面写过了几次操作Excel的,第一和第二次的都写的是main本机的.当然,你要套用到WEB当中完全可以,其实网上的实现方法很多,只要思路清晰,做一两个试验,就会很快的运用此JXL为自己服务了.
其实很多文字上的都是写好了的.这里只是贴出来,然后贴出做好的代码.
包:jxl.jar
/* 前面介绍了main的导入导出,都相当简单,没有经过一些特别的修饰,只是可以操作,这几天又闲的没事,就每天写一小点吧,今天肯定写不完,因为还想写点然后搞搞其他的东西,所以就写一部分吧. JXL针对导出Excel其实相当简单.流程大致相当清晰: 显示页面开始--->导出按钮(可以做成全部导出,或者导出你所想要的部分)--->选择你所要保存的目录--->开始导出(读数据-->写入Excel文件)--->完成 然后就是来看具体的程序操作了, 要下载首先还是要数据, 显示数据,全部都写在了JSP里面,其实就是简单的SQL语句而已,然后就是一个按钮,相当简单的操作,其实导出就跟main函数一个样,就是直接的指定导出就可以了. 这里唯一多的就是对于多了对Excel的处理,简单的看看Excel的样式,大家就会知道.有什么标题,页码(就是左下角的翻页),还有就是一些导入格式(内容标题,内容台头,还有就是字体,列的宽高等等). */
下面开始代码:
第一:jsp部分
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <%@ page import="java.util.*,java.sql.*"%> <% String webapp = request.getContextPath();%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>简单的导出操作</title> <mce:script type="text/javascript"><!-- //点击按钮就进行导出操作,简单吧,既不需要其他的操作,就是直接的简单的点击一下,其他就交给前台处理,当然只要有可能,你可以自己写不同的导出操作. function download(){ rul='<%=webapp%>/servlet/DownloadServlet?action=download'; window.location.href=rul; } // --></mce:script> </head> <body> <% try{ Class.forName("com.mysql.jdbc.Driver").newInstance(); Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:5885/excel","root","5885"); String sql = "select * from upload"; String sql1 = "select count(*) from upload"; Statement stat = conn.createStatement(); ResultSet resl = stat.executeQuery(sql1); resl.next(); int row = resl.getInt(1);//取得记录总数,可以不要,愿意想用其他的列表之类的列出来,后来用到了它自身的取得数据, //所以这个就是没有用的,但是后来没有删除掉,所以就保留着. resl = stat.executeQuery(sql); %> <p align="center">所有结果显示如下:</p> <p align="center"><input type="button" value="导出" onclick="download()"></input></p> <% if(row>0){ %> <table border="1" align="center" width="100%"> <tr><td width="30%" align="center"> ---编号--- </td><td width="40%" align="center"> ---姓名--- </td><td width="30%" align="center"> ---地址--- </td></tr> <% //for(int i = 0;i<=row;i++){ while(resl.next()){ %> <tr> <td><%=String.valueOf(resl.getInt(1)) %></td> <td><%=String.valueOf(resl.getString(2)) %></td> <td><%=String.valueOf(resl.getString(3)) %></td> </tr> <%} %> </table> <%}%> <% resl.close(); stat.close(); conn.close(); }catch(Exception e){ // } %> </body> </html>
第二:Java Servlet部分
package download; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.sql.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Vector; import jxl.Workbook; import jxl.write.Label; import jxl.write.WritableCellFormat; import jxl.write.WritableFont; import jxl.write.WritableWorkbook; import jxl.write.WriteException; @SuppressWarnings("serial") public class DownloadServlet extends HttpServlet { public DownloadServlet() { super(); } public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //准备工作, response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); //PrintWriter out = response.getWriter(); String flag = request.getParameter("action"); if(flag.equals("download")){ try{ Class.forName("com.mysql.jdbc.Driver").newInstance(); Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:5885/excel","root","5885"); String sql = "select * from upload"; Statement stat = conn.createStatement(); ResultSet resl = stat.executeQuery(sql); List list = toList(resl); String fileName = "downloadTest"; String sheetName = "第一页"; String[] titles = {"ID编号","姓名","住址"}; Vector vector = new Vector(); for(int i=0;i<list.size();i++){ Map map = (Map)list.get(i); String[] excelData = {String.valueOf(map.get("Id")),String.valueOf(map.get("name")),String.valueOf(map.get("address"))}; vector.add(excelData); } exportToExcel(response,fileName,sheetName,titles,vector); }catch(Exception e){ // } } //out.flush(); //out.close(); } public void init() throws ServletException { // Put your code here } //将result转换为list public List toList(ResultSet rs) { try { List list = new ArrayList(); ResultSetMetaData md = rs.getMetaData(); int columnCount = md.getColumnCount(); //Map rowData; while (rs.next()) { //rowData = new HashMap(columnCount); Map rowData = new HashMap(); for (int i = 1; i <= columnCount; i++) { rowData.put(md.getColumnName(i), rs.getObject(i)); } list.add(rowData); } return list; } catch(Exception ex) { ex.printStackTrace(); return null; } } //这里定义一个公共的方法,导出Excel文件. public void exportToExcel(HttpServletResponse res, String fileName, String sheetname, String[] titles, Vector vect) throws Exception { OutputStream os = null; try { os = res.getOutputStream(); //取得输出流 res.reset(); // 清空输出流 res.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xls"); //设定输出文件头 res.setContentType("application/msexcel"); //定义输出类型 } catch (IOException ex) { System.out.println("流操作错误:" + ex.getMessage()); } WritableWorkbook workbook = null; try { // 创建新的Excel 工作簿这个是哪里都必须有的,就是这些步骤,其实其他的相关操作,比如定义表头,定义标题,定义字体等等,都可以不要,因为只要有了个主架,能够写入数据,就够了. workbook = Workbook.createWorkbook(os); // 在Excel工作簿中建一工作表,其名为:第一页 jxl.write.WritableSheet wsheet = workbook.createSheet(sheetname, 0); // sheet(); //基本的就是创建一个 工作簿Excel.---> 然后就是这个Excel的页.--->最后写入数据. //中间可能有些修饰.具体的就按照自己的需求定义.查询API,很明显就能够得到,搜索网络,一大堆都是. //数据才是最主要的,一个标题,一个列名描述就够了,其他的设置其实没有必要, //设置每一列的宽度.第一个参数是列,第二个是多宽按厘米记, wsheet.setColumnView(0, 30);//第一列 wsheet.setColumnView(1, 30);//第二列 wsheet.setColumnView(2, 30);//第三列 WritableFont font = new WritableFont(WritableFont.ARIAL, 12, WritableFont.BOLD, false, jxl.format.UnderlineStyle.NO_UNDERLINE, jxl.format.Colour.BLACK); WritableCellFormat format = new WritableCellFormat(font); for (int i = 0; i < titles.length; i++) { Label wlabel1 = new Label(i, 0, String.valueOf(titles[i]), format); // 行、列、单元格中的文本、文本格式 wsheet.addCell(wlabel1); } font = new jxl.write.WritableFont(WritableFont.createFont("宋体"), 12, WritableFont.NO_BOLD, false, jxl.format.UnderlineStyle.NO_UNDERLINE, jxl.format.Colour.BLACK); format = new jxl.write.WritableCellFormat(font); for (int i = 1; i <= vect.size(); i++) { // 在索引0的位置创建行(最顶端的行) String[] sdata = (String[]) vect.elementAt(i - 1); for (int j = 0; j < sdata.length; j++) { // 在索引0的位置创建单元格(左上端) Label wlabel1 = new Label(j, i, sdata[j], format); // 行、列、单元格中的文本、文本格式 wsheet.addCell(wlabel1); } } workbook.write(); // 写入文件 workbook.close(); os.close(); } catch (WriteException ex1) { System.out.println("WriteException:" + ex1.getMessage()); } catch (IOException ex2) { System.out.println("IOException:" + ex2.getMessage()); } // res.flushBuffer(); } }
第三:WEB配置
</servlet> <servlet> <servlet-name>DownloadServlet</servlet-name> <servlet-class>download.DownloadServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>DownloadServlet</servlet-name> <url-pattern>/servlet/DownloadServlet</url-pattern> </servlet-mapping>
第四:数据库文件.(为了避免上传.所以给出来了)
# Host: localhost:5885 Database: excel # ------------------------------------------------------ # Server version 5.0.51b-community-nt DROP DATABASE IF EXISTS `excel`; CREATE DATABASE `excel` /*!40100 DEFAULT CHARACTER SET utf8 */; USE `excel`; # # Table structure for table test # CREATE TABLE `test` ( `Id` int(11) NOT NULL auto_increment, `name` varchar(20) default NULL, PRIMARY KEY (`Id`) ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8; CREATE TABLE `upload` ( `Id` int(8) NOT NULL default '0', `name` varchar(30) NOT NULL default '', `address` varchar(30) NOT NULL default '', PRIMARY KEY (`Id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; # # Dumping data for table upload # LOCK TABLES `upload` WRITE; /*!40000 ALTER TABLE `upload` DISABLE KEYS */; INSERT INTO `upload` VALUES (1,'1','1'); INSERT INTO `upload` VALUES (2,'2','2'); INSERT INTO `upload` VALUES (3,'3','3'); INSERT INTO `upload` VALUES (4,'4','4'); INSERT INTO `upload` VALUES (5,'5','5'); INSERT INTO `upload` VALUES (6,'6','6'); INSERT INTO `upload` VALUES (7,'7','7'); INSERT INTO `upload` VALUES (12,'11232','1231312'); INSERT INTO `upload` VALUES (13,'12313','123313'); INSERT INTO `upload` VALUES (14,'3214','321214'); INSERT INTO `upload` VALUES (15,'sdf15','132s15'); INSERT INTO `upload` VALUES (16,'1616','161616'); INSERT INTO `upload` VALUES (17,'fsd','fsdf'); INSERT INTO `upload` VALUES (18,'sd','fsdf'); INSERT INTO `upload` VALUES (19,'sdf','sdfsd'); INSERT INTO `upload` VALUES (20,'sdf','sdf'); INSERT INTO `upload` VALUES (21,'sdf','sdf'); INSERT INTO `upload` VALUES (22,'sdf','sdf'); INSERT INTO `upload` VALUES (23,'sdf','sdf'); INSERT INTO `upload` VALUES (24,'sdf','sdf'); INSERT INTO `upload` VALUES (25,'sdf','sdf'); INSERT INTO `upload` VALUES (26,'sdf','ssdf'); INSERT INTO `upload` VALUES (27,'sdf','sdf'); INSERT INTO `upload` VALUES (28,'sdf','sdf'); /*!40000 ALTER TABLE `upload` ENABLE KEYS */; UNLOCK TABLES;