jdbc导出数据库数据到Excel表格

package com.jiepu.docbuilder.poi;

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 java.io.File;
import java.io.FileOutputStream;
import java.sql.*;

public class ExcelDatabase
{
    public static void main(String[] args) throws Exception
    {
        Class.forName("com.mysql.jdbc.Driver");
        Connection connect = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/mysql" ,
                "root" ,
                "mysql0774mysql"
        );
        Statement statement = connect.createStatement();
        ResultSet resultSet = statement
                .executeQuery("select * from help_topic");
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet spreadsheet = workbook
                .createSheet("help_topic");
        XSSFRow row=spreadsheet.createRow(0);
        XSSFCell cell;

        // 获取列名 resultSet数据下标从1开始
        ResultSetMetaData metaData = resultSet.getMetaData();
        for (int i = 0; i < metaData.getColumnCount(); i++) {
            int index=i+1;
            String columnName = metaData.getColumnName(index);
            //System.out.println(columnName + "\t");
            cell=row.createCell(i);
            cell.getCellStyle().setWrapText(true);
            cell.setCellValue(columnName);
        }

        int i=1;
        while(resultSet.next())
        {
            row=spreadsheet.createRow(i);
            for (int j = 0; j< metaData.getColumnCount(); j++) {
                int index=j+1;
                cell=row.createCell(j);
                /*
                XSSFCellStyle cellStyle=workbook.createCellStyle();
                cellStyle.setAlignment(HorizontalAlignment.LEFT);
                cellStyle.setVerticalAlignment(VerticalAlignment.TOP);
                cellStyle.setWrapText(true);
                cell.setCellStyle(cellStyle);
                */
                cell.setCellValue(resultSet.getString(index));
            }
            i++;
        }

        FileOutputStream out = new FileOutputStream(new File("excel_database.xlsx"));
        workbook.write(out);
        out.close();
        System.out.println("excel_database.xlsx written successfully");
    }
}

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值