您的位置:首页 > 编程语言 > Java开发

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

2017-09-15 22:31 453 查看
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包
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: