使用java的图像化界面链接数据库实现excel的导入导出
时间: 2024-03-14 17:42:52 浏览: 74
用java实现把excel数据导入到mysql数据库中.pdf
好的,我可以帮你解决这个问题。
首先,需要使用 Java 的 GUI 工具包来构建图像化界面,常用的有 Swing 和 JavaFX。在这里,我以 Swing 为例,介绍如何实现 excel 的导入导出。
1. 引入相关的 jar 包
需要引入以下 jar 包:
- `mysql-connector-java-x.x.xx.jar`:MySQL 的 JDBC 驱动程序;
- `poi-ooxml-x.x.jar`:Apache POI 的 OOXML 类库,用于读写 excel 文件;
- `poi-ooxml-schemas-x.x.jar`:Apache POI 的 OOXML 类库的依赖类库;
- `xmlbeans-x.x.jar`:Apache POI 的 OOXML 类库的依赖类库。
可以在 Maven 中央仓库或 Apache 官网下载这些 jar 包。
2. 创建图像化界面
使用 Swing 创建图像化界面,可以使用 JFrame、JPanel、JButton、JLabel 等组件。在这里,我以一个简单的窗口为例,界面上有两个按钮,一个用于导入 excel 文件,一个用于导出数据到 excel 文件。
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class MainFrame extends JFrame implements ActionListener {
private JButton btnImport, btnExport;
public MainFrame() {
setTitle("Excel Import/Export");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
JPanel panel = new JPanel(new GridLayout(2, 1, 10, 10));
btnImport = new JButton("Import from Excel");
btnExport = new JButton("Export to Excel");
btnImport.addActionListener(this);
btnExport.addActionListener(this);
panel.add(btnImport);
panel.add(btnExport);
getContentPane().add(panel, BorderLayout.CENTER);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnImport) {
// 导入 excel 文件
} else if (e.getSource() == btnExport) {
// 导出数据到 excel 文件
}
}
public static void main(String[] args) {
new MainFrame().setVisible(true);
}
}
```
3. 导入 excel 文件
在按钮的 ActionListener 中,实现导入 excel 文件的功能。可以使用 Apache POI 来读取 excel 文件中的数据,并将其插入到 MySQL 数据库中。
```java
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class MainFrame extends JFrame implements ActionListener {
private JButton btnImport, btnExport;
public MainFrame() {
setTitle("Excel Import/Export");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
JPanel panel = new JPanel(new GridLayout(2, 1, 10, 10));
btnImport = new JButton("Import from Excel");
btnExport = new JButton("Export to Excel");
btnImport.addActionListener(this);
btnExport.addActionListener(this);
panel.add(btnImport);
panel.add(btnExport);
getContentPane().add(panel, BorderLayout.CENTER);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnImport) {
// 导入 excel 文件
JFileChooser fileChooser = new JFileChooser();
int result = fileChooser.showOpenDialog(this);
if (result == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
try (FileInputStream fis = new FileInputStream(file)) {
Workbook workbook = new XSSFWorkbook(fis);
Sheet sheet = workbook.getSheetAt(0);
for (Row row : sheet) {
String name = row.getCell(0).getStringCellValue();
int age = (int) row.getCell(1).getNumericCellValue();
String gender = row.getCell(2).getStringCellValue();
insertDataToDatabase(name, age, gender);
}
JOptionPane.showMessageDialog(this, "Import succeeded!");
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, "Import failed: " + ex.getMessage());
}
}
} else if (e.getSource() == btnExport) {
// 导出数据到 excel 文件
}
}
private void insertDataToDatabase(String name, int age, String gender) throws SQLException {
String url = "jdbc:mysql://localhost:3306/test?useSSL=false";
String username = "root";
String password = "123456";
String sql = "INSERT INTO users (name, age, gender) VALUES (?, ?, ?)";
try (Connection conn = DriverManager.getConnection(url, username, password);
PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setString(1, name);
pstmt.setInt(2, age);
pstmt.setString(3, gender);
pstmt.executeUpdate();
}
}
public static void main(String[] args) {
new MainFrame().setVisible(true);
}
}
```
在 insertDataToDatabase 方法中,使用 JDBC 连接 MySQL 数据库,并将 excel 文件中的数据插入到数据库中。
4. 导出数据到 excel 文件
在 ActionListener 中,实现导出数据到 excel 文件的功能。可以使用 Apache POI 来创建 excel 文件,并将 MySQL 数据库中的数据写入到 excel 文件中。
```java
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class MainFrame extends JFrame implements ActionListener {
private JButton btnImport, btnExport;
public MainFrame() {
setTitle("Excel Import/Export");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
JPanel panel = new JPanel(new GridLayout(2, 1, 10, 10));
btnImport = new JButton("Import from Excel");
btnExport = new JButton("Export to Excel");
btnImport.addActionListener(this);
btnExport.addActionListener(this);
panel.add(btnImport);
panel.add(btnExport);
getContentPane().add(panel, BorderLayout.CENTER);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnImport) {
// 导入 excel 文件
JFileChooser fileChooser = new JFileChooser();
int result = fileChooser.showOpenDialog(this);
if (result == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
try (FileInputStream fis = new FileInputStream(file)) {
Workbook workbook = new XSSFWorkbook(fis);
Sheet sheet = workbook.getSheetAt(0);
for (Row row : sheet) {
String name = row.getCell(0).getStringCellValue();
int age = (int) row.getCell(1).getNumericCellValue();
String gender = row.getCell(2).getStringCellValue();
insertDataToDatabase(name, age, gender);
}
JOptionPane.showMessageDialog(this, "Import succeeded!");
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, "Import failed: " + ex.getMessage());
}
}
} else if (e.getSource() == btnExport) {
// 导出数据到 excel 文件
JFileChooser fileChooser = new JFileChooser();
int result = fileChooser.showSaveDialog(this);
if (result == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
try (FileOutputStream fos = new FileOutputStream(file);
Workbook workbook = new XSSFWorkbook()) {
Sheet sheet = workbook.createSheet("Users");
Row headerRow = sheet.createRow(0);
Cell nameHeader = headerRow.createCell(0);
nameHeader.setCellValue("Name");
Cell ageHeader = headerRow.createCell(1);
ageHeader.setCellValue("Age");
Cell genderHeader = headerRow.createCell(2);
genderHeader.setCellValue("Gender");
int rowNum = 1;
for (User user : getUsersFromDatabase()) {
Row row = sheet.createRow(rowNum++);
Cell nameCell = row.createCell(0);
nameCell.setCellValue(user.getName());
Cell ageCell = row.createCell(1);
ageCell.setCellValue(user.getAge());
Cell genderCell = row.createCell(2);
genderCell.setCellValue(user.getGender());
}
workbook.write(fos);
JOptionPane.showMessageDialog(this, "Export succeeded!");
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, "Export failed: " + ex.getMessage());
}
}
}
}
private void insertDataToDatabase(String name, int age, String gender) throws SQLException {
String url = "jdbc:mysql://localhost:3306/test?useSSL=false";
String username = "root";
String password = "123456";
String sql = "INSERT INTO users (name, age, gender) VALUES (?, ?, ?)";
try (Connection conn = DriverManager.getConnection(url, username, password);
PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setString(1, name);
pstmt.setInt(2, age);
pstmt.setString(3, gender);
pstmt.executeUpdate();
}
}
private List<User> getUsersFromDatabase() throws SQLException {
String url = "jdbc:mysql://localhost:3306/test?useSSL=false";
String username = "root";
String password = "123456";
String sql = "SELECT name, age, gender FROM users";
try (Connection conn = DriverManager.getConnection(url, username, password);
PreparedStatement pstmt = conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery()) {
List<User> users = new ArrayList<>();
while (rs.next()) {
String name = rs.getString("name");
int age = rs.getInt("age");
String gender = rs.getString("gender");
users.add(new User(name, age, gender));
}
return users;
}
}
public static void main(String[] args) {
new MainFrame().setVisible(true);
}
}
class User {
private String name;
private int age;
private String gender;
public User(String name, int age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String getGender() {
return gender;
}
}
```
在 getUsersFromDatabase 方法中,使用 JDBC 连接 MySQL 数据库,并从 users 表中获取数据,返回一个包含 User 对象的 List。
在导出数据到 excel 文件时,创建一个 Sheet 对象,并使用 createRow 和 createCell 方法创建表头和数据行,然后将数据写入到 excel 文件中。
阅读全文