在Java中,我們可以使用一些工具,例如Apache POI和JExcelAPI,將MySQL數(shù)據(jù)庫(kù)中的數(shù)據(jù)導(dǎo)出到Excel電子表格中。以下是使用Apache POI的簡(jiǎn)單示例:
try { // 創(chuàng)建Workbook對(duì)象,這將創(chuàng)建一個(gè)新的空Excel文件 Workbook workbook = new XSSFWorkbook(); // 創(chuàng)建工作表對(duì)象 Sheet sheet = workbook.createSheet("MySQL Data"); // 連接MySQL數(shù)據(jù)庫(kù) Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "username", "password"); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM mytable"); // 將MySQL結(jié)果集中的數(shù)據(jù)寫(xiě)入Excel電子表格中 Row headerRow = sheet.createRow(0); 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)); } int rowNumber = 1; while (rs.next()) { Row row = sheet.createRow(rowNumber++); for (int i = 1; i<= columnCount; i++) { Cell cell = row.createCell(i - 1); cell.setCellValue(rs.getString(i)); } } // 將Excel文件保存到磁盤(pán)上 FileOutputStream outputStream = new FileOutputStream("mysql_data.xlsx"); workbook.write(outputStream); outputStream.close(); // 關(guān)閉數(shù)據(jù)庫(kù)連接 rs.close(); stmt.close(); conn.close(); System.out.println("MySQL數(shù)據(jù)已成功導(dǎo)出到Excel文件中!"); } catch (Exception e) { e.printStackTrace(); }
上述代碼將MySQL數(shù)據(jù)庫(kù)"mydatabase"中的"mytable"表中的數(shù)據(jù)導(dǎo)出到名為"mysql_data.xlsx"的Excel電子表格中。您可以根據(jù)需要修改連接字符串和查詢字符串以滿足您的需求。
注意,此示例需要在項(xiàng)目中包含Apache POI庫(kù)的JAR文件。