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");
}
}
jdbc导出数据库数据到Excel表格
最新推荐文章于 2024-07-26 10:05:08 发布