因为要做一个报表的功能,要把数据展示到文档上。这就不得不用到这段代码了
错误一:驱动问题
解决办法:找了很多方法 ,什么在jre的lib的ext下放驱动包,
还有的检查url
找了好久,想到应该主动加载驱动包
Class.forName("com.mysql.jdbc.Driver");
package cm.wql.Test;
import jxl.Workbook;
import jxl.write.Number;
import jxl.write.*;
import jxl.write.biff.RowsExceededException;
import java.io.File;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class Test2 {
public static void main(String[] args) throws RowsExceededException, WriteException, IOException, ClassNotFoundException {
//1. 导出Excel的路径
String filePath = "E:/export.xls";
WritableWorkbook wwb =null;
try {
wwb = Workbook.createWorkbook(new File(filePath));
} catch (Exception e) {
e.printStackTrace();
}
//创建Excel表的"学生"区域的数据
WritableSheet sheet = wwb.createSheet("学生信息",0);//或者rwb.getSheet(0)获取第一个区域
//设置titles
String[] titles={"编号","姓名","地址"};
//单元格
Label label=null;
//第一行设置列名
for(int i=0;i<titles.length;i++){
label=new Label(i,0,titles[i]);
//7:添加单元格
sheet.addCell(label);
System.out.println("00000000000099");
}
try {
//2. 连接数据库的几行代码
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/crm?useUnicode=true&characterEncoding=UTF-8";
String sql = "select * from student";
con = DriverManager.getConnection(url, "root", "root");
ps = con.prepareStatement(sql);// SQL预处理
rs = ps.executeQuery();
//ResultSet是数据库中的数据,将其转换为List类型
List<Student> list = new ArrayList<Student>();
while(rs.next()){
Student stu = new Student();
stu.setId(rs.getInt("id"));
stu.setName(rs.getString("name"));
stu.setAddr(rs.getString("addr"));//不要写成rs.getAddr ,getAddr只是student对象才有的方法
list.add(stu);
}
ps.close();
con.close();
for(int i = 0; i<list.size(); i++){
//Number对应数据库的int类型数据
sheet.addCell(new Number(0,i+1,list.get(i).getId()));//0 列,i+1行
//Label对应数据库String类型数据
sheet.addCell(new Label(1,i+1,list.get(i).getName()));//1列,i+1行
//Label对应数据库String类型数据
sheet.addCell(new Label(2,i+1,list.get(i).getAddr()));//2列,i+1行
}
wwb.write();
} catch (SQLException e) {
e.printStackTrace();
}finally{
wwb.close();
}
}
}
<dependency>
<groupId>net.sourceforge.jexcelapi</groupId>
<artifactId>jxl</artifactId>
<version>2.6.12</version>
</dependency>