- Java 编程示例
- 示例 - 主页
- 示例 - 环境
- 示例 - 字符串
- 示例 - 数组
- 示例 - 日期和时间
- 示例 - 方法
- 示例 - 文件
- 示例 - 目录
- 示例 - 异常
- 示例 - 数据结构
- 示例 - 集合
- 示例 - 网络
- 示例 - 线程
- 示例 - 小程序
- 示例 - 简单 GUI
- 示例 - JDBC
- 示例 - 正则表达式
- 示例 - Apache PDF Box
- 示例 - Apache POI PPT
- 示例 - Apache POI Excel
- 示例 - Apache POI Word
- 示例 - OpenCV
- 示例 - Apache Tika
- 示例 - iText
- Java 教程
- Java - 教程
- Java 实用资源
- Java - 快速指南
- Java - 实用资源
如何使用 Java 将数据从数据库插入到电子表格
问题描述
如何使用 Java 将数据从数据库插入到电子表格。
解决方案
以下是使用 Java 将数据从数据库插入到电子表格的程序。
import java.io.File; import java.io.FileOutputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; 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; public class InsertDataFromDataBaseToSpreadSheet { public static void main(String[] args) throws Exception { //Connecting to the database Class.forName("com.mysql.jdbc.Driver"); Connection connect = DriverManager.getConnection( "jdbc:mysql://127.0.0.1:3306/details", "root" , "password"); //Getting data from the table emp_tbl Statement statement = connect.createStatement(); ResultSet resultSet = statement.executeQuery("select * from student_data"); //Creating a Work Book XSSFWorkbook workbook = new XSSFWorkbook(); //Creating a Spread Sheet XSSFSheet spreadsheet = workbook.createSheet("employe db"); XSSFRow row = spreadsheet.createRow(1); XSSFCell cell; cell = row.createCell(1); cell.setCellValue("EMP ID"); cell = row.createCell(2); cell.setCellValue("EMP NAME"); cell = row.createCell(3); cell.setCellValue("DEG"); cell = row.createCell(4); cell.setCellValue("SALARY"); cell = row.createCell(5); cell.setCellValue("DEPT"); int i = 2; while(resultSet.next()) { row = spreadsheet.createRow(i); cell = row.createCell(1); cell.setCellValue(resultSet.getInt("ID")); cell = row.createCell(2); cell.setCellValue(resultSet.getString("NAME")); cell = row.createCell(3); cell.setCellValue(resultSet.getString("BRANCH")); cell = row.createCell(4); cell.setCellValue(resultSet.getString("PERCENTAGE")); cell = row.createCell(5); cell.setCellValue(resultSet.getString("EMAIL")); i++; } FileOutputStream out = new FileOutputStream( new File("C:/poiexcel/exceldatabase.xlsx")); workbook.write(out); out.close(); System.out.println("exceldatabase.xlsx written successfully"); } }
数据库
mysql> select * from student_data; +----+--------+--------+------------+---------------------+ | ID | NAME | BRANCH | PERCENTAGE | EMAIL | +----+--------+--------+------------+---------------------+ | 1 | Ram | IT | 85 | [email protected] | | 2 | Rahim | EEE | 95 | [email protected] | | 3 | Robert | ECE | 90 | [email protected] | +----+--------+--------+------------+---------------------+ 3 rows in set (0.00 sec)
结果
java_apache_poi_excel
广告