Java利用POI将数据库表导出到Excel

来源:互联网 发布:淘宝被挤爆了图片 编辑:程序博客网 时间:2024/06/06 13:00


package outExcel;


import java.io.FileOutputStream;
import java.sql.DriverManager;
import java.sql.ResultSet;


import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;


import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;




public class toExcel {

public final static String outputFile="D:\\outFile\\outFile.xlsx";   //创建的Excel文件路径


    public final static String url="jdbc:mysql://localhost:3308/shcydb"; //数据库路径


    public final static String user="root"; //数据库用户名


    public final static String password="mysql"; //数据库密码


    public static void main(String[] args) {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection conn=(Connection) DriverManager.getConnection(url, user, password);
            Statement stat = (Statement) conn.createStatement();
            ResultSet resultSet = stat.executeQuery("SELECT * FROM news;");   // 查询表
            XSSFWorkbook workbook=new XSSFWorkbook();
            XSSFSheet sheet=workbook.createSheet("news");
            XSSFRow row = sheet.createRow((short)0);
            XSSFCell cell=null;
            cell=row.createCell((short)0);      //所需生成的列名
            cell.setCellValue("news_id");
            cell=row.createCell((short)1);
            cell.setCellValue("user_id");
            cell=row.createCell((short)2);
            cell.setCellValue("news_content");
            cell=row.createCell((short)3);
            cell.setCellValue("news_crtdt");
            int i=1;
            while(resultSet.next())
            {
                row=sheet.createRow(i);
                cell=row.createCell(0);
                cell.setCellValue(resultSet.getString("news_id"));         //所需生成的列名
                cell=row.createCell(1);
                cell.setCellValue(resultSet.getString("user_id"));
                cell=row.createCell(2);
                cell.setCellValue(resultSet.getString("news_content"));
                cell=row.createCell(3);
                cell.setCellValue(resultSet.getString("news_crtdt"));
                i++;
             }
            FileOutputStream FOut = new FileOutputStream(outputFile);
            workbook.write(FOut);
            FOut.flush();
            FOut.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}


复件14个jar包


原创粉丝点击