首先需要导入1个jxl.jar,可以去官网下载(百度去找地址).
下面实例——
No.1
package com.jxl;
import jxl.write.*;
import jxl.write.Number;
import jxl.write.biff.RowsExceededException;
import jxl.*;
import java.io.*;
import java.util.*;
public class Jxl {
public static void main(String[] args) {
try {
WritableWorkbook wb=Workbook.createWorkbook(new File("output.xls"));//创建工作簿
WritableSheet ws=wb.createSheet("First Sheet", 0);//创建第一张表
Label l=new Label(0,2,"A lable record");//数据
try {
ws.addCell(l);//增加到表的单元格中
} catch (RowsExceededException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (WriteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Number n=new Number(3,4,3.15);//数据
try {
ws.addCell(n);//增加到表的单元格中
} catch (RowsExceededException e) {
e.printStackTrace();
} catch (WriteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
WritableFont font=new WritableFont(WritableFont.ARIAL,10);//创建字体
WritableCellFormat format=new WritableCellFormat(font);//创建单元格样式
Label label2=new Label(1,0,"Arial",format);//数据
try {
ws.addCell(label2);//加到表中
} catch (RowsExceededException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (WriteException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Date now=Calendar.getInstance().getTime();//获取当前时间
DateFormat dformat=new DateFormat("dd MMM yyyy hh:mm:ss");//时间的样式
WritableCellFormat dateformat=new WritableCellFormat(dformat);//写到单元格中的样式
DateTime datecell=new DateTime(0,6,now,dateformat);//数据
try {
ws.addCell(datecell);//加到表中
} catch (RowsExceededException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (WriteException e1) {
e1.printStackTrace();
}
wb.write();//写完
try {
wb.close();//关闭工作簿
} catch (WriteException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
No.2——访问数据库导出
package com.jxl2;
import java.io.*;
import jxl.write.*;
import jxl.*;
import java.sql.*;
public class Jx {
public static void main(String[] args) {
Connection ct=null;
PreparedStatement ps=null;
ResultSet rs=null;
try{
WritableWorkbook wbook=Workbook.createWorkbook(new File("out.xls"));
WritableSheet ws=wbook.createSheet("Fist Sheet", 0);
Label l=new Label(0,0,"id");
ws.addCell(l);
Label l2=new Label(1,0,"name");
ws.addCell(l2);
Class.forName("com.mysql.jdbc.Driver");
ct=DriverManager.getConnection("jdbc:mysql://localhost:3306/users","root","123456");
ps=ct.prepareStatement("select * from user");
rs=ps.executeQuery();
if(rs.next()){
String a=rs.getString(1);
for(int i=1;i<5;i++){
Label l3=new Label(0,i,a);
System.out.println("out:"+a);
ws.addCell(l3);
}
}
wbook.write();
wbook.close();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(rs!=null){
rs.close();
rs=null;
}if(ps!=null){
ps.close();
ps=null;
}if(ct!=null){
ct.close();
ct=null;
}
}catch(Exception e){
e.printStackTrace();
}
}
}
}