所用Jar包
1. sqljdbc4.jar
連接數據庫的Jar包(根據數據庫的不同進行選擇,我用的SqlServer2008)
2.Jxl.jar
訪問Excel的Jar包
注意:支持以.xls結尾的Excel文件,可能不支持.xlsx結尾的
實現效果:
數據庫數據:
導出的Excel:
完整代碼:
導出的核心代碼就四五行
類里需要import的包也都貼上:
package xsl; import java.io.File; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import jxl.Workbook; import jxl.write.Label; import jxl.write.WritableSheet; import jxl.write.WritableWorkbook; import jxl.write.WriteException; import jxl.write.biff.RowsExceededException; public class Export { public static void main(String[] args) throws RowsExceededException, WriteException, IOException { //1. 導出Excel的路徑 String filePath = "C:/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)獲取第一個區域 try { //2. 連接數據庫的幾行代碼 Connection con = null; PreparedStatement ps = null; ResultSet rs = null; String url = "jdbc:sqlserver://localhost:1433;DatabaseName=test;"; String sql = "select * from students"; con = DriverManager.getConnection(url, "sa", "123456"); 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")); list.add(stu); } ps.close(); con.close(); for(int i = 0; i<list.size(); i++){ //Number對應數據庫的int類型數據 sheet.addCell(new jxl.write.Number(0,i,list.get(i).getId())); //Label對應數據庫String類型數據 sheet.addCell(new Label(1,i,list.get(i).getName())); } wwb.write(); } catch (SQLException e) { e.printStackTrace(); }finally{ wwb.close(); } } }
寫的比較亂,但是可運行,因為我也是剛學會,才看了一會兒,以后深入了解后,再來整理