java生成Excel文件(测试通过)

来源:互联网 发布:华侨大学研究生知乎 编辑:程序博客网 时间:2024/05/02 01:53

调试了好长时间终于可以了

一、DatabaseBean.java

package sraims.dao;

import java.sql.*;

public class DatabaseBean {
 private static String driverName = "com.mysql.jdbc.Driver";

 private static String username = "root";

 private static String password = "123456";

 private static String databaseURL = "jdbc:mysql://localhost:3306/sraims?

useUnicode=true&characterEncoding=UTF-8";

 /**
  * 获取数据库连接Connection对象
  * 无法获取则返回null
  * @return
  */
 public static Connection getConnection() {
 Connection conn = null;
 try {
 // 加载驱动程序
 Class.forName(driverName);
 // 获取数据库连接
 conn = DriverManager.getConnection(databaseURL, username, password);
 } catch (ClassNotFoundException cnfe) {
 // 无法找到驱动程序
 cnfe.printStackTrace();
 conn = null;
 } catch (SQLException sqle) {
 // 数据库发生异常
 sqle.printStackTrace();
 conn = null;
 }
 return conn;
 }
 

 /**
  * 关闭连接
  * 按次序释放资源
  * @param conn
  * @param stmt
  * @param rs
  */
 public static void close(Connection conn, PreparedStatement pstmt, ResultSet rs) {
 try {
 if (rs != null)
 rs.close();
 } catch (Exception rse) {
 rse.printStackTrace();
 }

 try {
 if (pstmt != null)
 pstmt.close();
 } catch (Exception stmte) {
 stmte.printStackTrace();
 }

 try {
 if (conn != null)
 conn.close();
 } catch (Exception conne) {
 conne.printStackTrace();
 }
 }
}


二 、Excel.java

package excel;
 
 
import java.io.*;
import java.sql.*;

import javax.sql.rowset.CachedRowSet;
import com.sun.rowset.CachedRowSetImpl;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;

public class Excel {
 private static Connection conn=null;
    private static PreparedStatement pstmt=null;
    private static ResultSet rs=null;
    private static CachedRowSet crs;
    public CachedRowSet GetResult(String sql)throws  SQLException{
      try {
    conn=DatabaseBean.getConnection();
     pstmt=conn.prepareStatement(sql);
     rs=pstmt.executeQuery();
     crs=new CachedRowSetImpl();
     crs.populate(rs);  
    return  crs;
   } catch (Exception e) {
    // TODO: handle exception
    return null;
   }finally{
    DatabaseBean.close(conn, pstmt, rs);
   }
   
    }
 public void getExcelResult(String sql, OutputStream os)
   throws SQLException, IOException, WriteException {

  // 首先获取结果集
  // 这里获取RowSet的方法
  CachedRowSet crs = this.GetResult(sql);

  // 然后将结果集转化为Excel输出
  // 初始化工作

  WritableWorkbook wwb = null;

  try {
   wwb = Workbook.createWorkbook(os);

   // 创建工作表
   jxl.write.WritableSheet ws = wwb.createSheet("Sheet1", 0);
   // 逐行添加数据
   int i = 0;
   while (crs.next()) {
    for (int j = 1; j <= crs.getMetaData().getColumnCount(); j++) {
     String s = crs.getString(j);
     Label labelC = new Label(j - 1, i, s);
     ws.addCell(labelC);
    }
    i++;
   }

  } catch (Exception e) {
   //logger.error("export excel error:" + e);
   e.printStackTrace();
  } finally {
   if (wwb != null) {
    wwb.write();
    wwb.close();
   }
  }

 }
 }
 

test.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<html>
 <head>
<title>css立体层</title>
</head>
<body>
 <form action="excel.jsp" method="post">
 <table>
 <tr>
 <td>
 <h6>请输入Sql语句</h6>
 </td>
 </tr>
 <tr>
 <td>
 <input type="text" name="sql" >
 </td>
 </tr>
  <tr>
 <td>
 <input type="submit" value="Submit" >
 </td>
 </tr>
 </table>
 </form>
</body>
</html>

excel.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@page import="excel.Excel" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <%  out.print(request.getParameter("sql"));
        Excel excel=new Excel();
        response.reset();
        response.setContentType("application/vnd.ms-excel"); 
       // String sql="select *  from tbit_links ";    
        String sql=request.getParameter("sql");
        excel.getExcelResult(sql,response.getOutputStream());
    %>   
</body>
</html>

写入数据的时候注意的格式


(1)添加的字体样式
jxl.write.WritableFont wf = new jxl.write.WritableFont(WritableFont.TIMES, 18, WritableFont.BOLD, true);
WritableFont()方法里参数说明:
这个方法算是一个容器,可以放进去好多属性
第一个: TIMES是字体大小,他写的是18
第二个: BOLD是判断是否为斜体,选择true时为斜体
第三个: ARIAL
第四个: UnderlineStyle.NO_UNDERLINE 下划线
第五个: jxl.format.Colour.RED 字体颜色是红色的

jxl.write.WritableCellFormat wcfF = new jxl.write.WritableCellFormat(wf);

jxl.write.Label labelC = new jxl.write.Label(0, 0, "This is a Label cell",wcfF);
ws.addCell(labelC);
在Label()方法里面有三个参数
第一个是代表列数,
第二是代表行数,
第三个代表要写入的内容
第四个是可选项,是输入这个label里面的样式
然后通过写sheet的方法addCell()把内容写进sheet里面。

(2)添加带有formatting的Number对象
jxl.write.NumberFormat nf = new jxl.write.NumberFormat("#.##");


(3)添加Number对象
(3.1)显示number对象数据的格式

jxl.write.NumberFormat nf = new jxl.write.NumberFormat("#.##");
jxl.write.WritableCellFormat wcfN = new jxl.write.WritableCellFormat(nf);

jxl.write.Number labelNF = new jxl.write.Number(1, 1, 3.1415926, wcfN);
ws.addCell(labelNF);
Number()方法参数说明:
前两上表示输入的位置
第三个表示输入的内容


(4)添加Boolean对象
jxl.write.Boolean labelB = new jxl.write.Boolean(0, 2, false);
ws.addCell(labelB);


(5)添加DateTime对象
jxl.write.DateTime labelDT = new jxl.write.DateTime(0, 3, new java.util.Date());
ws.addCell(labelDT);
DateTime()方法的参数说明
前两个表示输入的位置
第三个表示输入的当前时间


(6)添加带有formatting的DateFormat对象
这个显示当前时间的所有信息,包括年月日小时分秒
jxl.write.DateFormat df = new jxl.write.DateFormat("dd MM yyyy hh:mm:ss");
jxl.write.WritableCellFormat wcfDF = new jxl.write.WritableCellFormat(df);
jxl.write.DateTime labelDTF = new jxl.write.DateTime(1, 3, new java.util.Date(), wcfDF);
ws.addCell(labelDTF);

(7)添加带有字体颜色Formatting的对象

 

jxl.write.WritableFont wfc = new jxl.write.WritableFont(WritableFont.ARIAL, 10, WritableFont.NO_BOLD, false,UnderlineStyle.NO_UNDERLINE, jxl.format.Colour.RED);
jxl.write.WritableCellFormat wcfFC = new jxl.write.WritableCellFormat(wfc);

import="jxl.format.*
jxl.write.WritableFont wfc = new jxl.write.WritableFont(WritableFont.ARIAL,20,WritableFont.BOLD,false,UnderlineStyle.NO_UNDERLINE,jxl.format.Colour.GREEN);

(8)设置单元格样式

jxl.write.WritableCellFormat wcfFC = new jxl.write.WritableCellFormat(wfc);
wcfFC.setBackGround(jxl.format.Colour.RED);//设置单元格的颜色为红色
wcfFC = new jxl.write.Label(6,0,"i love china",wcfFC);

由于种种原因 我的源码不在了 向朋友们道歉 上面我把与数据库连接的代码贴出来了 希望你们用的上