可以使用Apache POI库来实现将数据库中的数据导出成Excel文件。以下是一个简单的示例代码:
import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExportToExcel {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/database_name";
String user = "username";
String password = "password";
String query = "SELECT * FROM table_name";
try (Connection conn = DriverManager.getConnection(url, user, password);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query)) {
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Data");
int rowNum = 0;
Row headerRow = sheet.createRow(rowNum++);
ResultSetMetaData metaData = rs.getMetaData();
int columnCount = metaData.getColumnCount();
for (int i = 1; i <= columnCount; i++) {
Cell cell = headerRow.createCell(i - 1);
cell.setCellValue(metaData.getColumnName(i));
}
while (rs.next()) {
Row dataRow = sheet.createRow(rowNum++);
for (int i = 1; i <= columnCount; i++) {
Cell cell = dataRow.createCell(i - 1);
cell.setCellValue(rs.getString(i));
}
}
FileOutputStream outputStream = new FileOutputStream("data.xlsx");
workbook.write(outputStream);
workbook.close();
System.out.println("Data exported successfully.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
请替换url
,user
,password
,query
,database_name
,table_name
和输出文件名data.xlsx
为你自己的数据库连接信息和表信息。
运行这段代码将会将指定表的数据导出成名为data.xlsx
的Excel文件。