Java 简易操作Excel

首先,我们需要创建一个数据库表来存储这些单词及其相关信息。以下是一个简单的SQL语句示例,用于创建这样一个表:

```sql

CREATE TABLE EnglishWords (
    id INT AUTO_INCREMENT PRIMARY KEY,
    word VARCHAR(255) NOT NULL,
    phonetic TEXT NOT NULL,
    chinese_meaning TEXT NOT NULL,
    example_sentence TEXT NOT NULL,
    example_translation TEXT NOT NULL
);


```

这个表`EnglishWords`有六个字段:
- `id`:单词的序号,自动增长的主键。
- `word`:单词本身。
- `phonetic`:单词的音标。
- `chinese_meaning`:单词的中文含义。
- `example_sentence`:单词的例句。
- `example_translation`:例句的中文释义。

接下来,我们将之前生成的10个单词插入到这个表中:

```sql

INSERT INTO EnglishWords (word, phonetic, chinese_meaning, example_sentence, example_translation) VALUES
('Abyss', 'əˈbɪs', '深渊;无底洞', 'She stared into the abyss, contemplating the vastness of the universe.', '她凝视着深渊,沉思着宇宙的浩瀚。'),
('Cataclysm', 'ˈkætəklɪzəm', '大洪水;灾难', 'The city was devastated by the cataclysm, with buildings reduced to rubble.', '城市被灾难摧毁,建筑物变成了废墟。'),
('Ephemeral', 'ɪˈfemərəl', '短暂的;朝生暮死的', 'The beauty of the sunset was ephemeral, vanishing as quickly as it appeared.', '日落之美是短暂的,它出现得快,消失得也快。'),
('Horizon', 'həˈraɪzən', '地平线;范围', 'The new technology expanded the horizons of what was possible in the field.', '这项新技术扩大了该领域可能性的范围。'),
('Inevitable', 'ɪnˈevɪtəbl', '不可避免的', 'It seemed inevitable that the two teams would meet in the championship final.', '这两支队伍似乎不可避免地会在冠军决赛中相遇。'),
('Juxtapose', 'ˈdʒʌkstəpəʊz', '并置;并列', 'The artist juxtaposed bright colors with dark ones to create a striking effect.', '艺术家将明亮的颜色与深色并置,以创造引人注目的效果。'),
('Kaleidoscope', 'kəˈlaɪdəskəʊp', '万花筒', 'Life is like a kaleidoscope, constantly changing patterns and colors.', '生活就像万花筒,不断变化的图案和颜色。'),
('Lethargic', 'ləˈθɑːdʒɪk', '昏睡的;倦怠的', 'After the long flight, he felt lethargic and needed a nap.', '长途飞行后,他感到昏昏欲睡,需要小睡一会儿。'),
('Mosaic', 'məʊˈzeɪɪk', '马赛克;镶嵌艺术', 'The ancient mosaic on the floor depicted scenes from Roman mythology.', '地板上的古老马赛克描绘了罗马神话中的场景。'),
('Nuance', 'ˈnjuːɑːns', '细微差别;语气', 'The artist captured the nuances of light and shadow in the painting.', '艺术家在画作中捕捉到了光影的细微差别。');


```

最后,我们可以使用以下SQL语句来显示表中的所有数据:

```sql

SELECT * FROM EnglishWords;


```

这个查询将返回表`EnglishWords`中的所有记录,包括每个单词的所有信息。请注意,实际的数据库操作需要在数据库管理工具或通过编程接口执行。

要将MySQL数据库中的数据写入Excel文件,你可以使用Java的一些库,如Apache POI。下面是一个示例代码,演示如何实现这个功能。这个示例假设你已经有了一个名为`EnglishWords`的表,并且表中包含了之前插入的数据。

首先,确保你的`pom.xml`文件中包含了Apache POI的依赖:

```xml

<!-- Apache POI -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>版本号</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>版本号</version>
</dependency>


```

然后,你可以使用以下Java代码来实现将数据写入Excel文件的功能:```java

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class ExportToExcel {

    public static void exportDataToExcel() throws IOException {
        // 数据库连接信息
        String url = "jdbc:mysql://localhost:3306/你的数据库名";
        String user = "用户名";
        String password = "密码";

        // 创建Excel工作簿
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("EnglishWords");

        // 设置标题行
        Row titleRow = sheet.createRow(0);
        titleRow.createCell(0).setCellValue("ID");
        titleRow.createCell(1).setCellValue("Word");
        titleRow.createCell(2).setCellValue("Phonetic");
        titleRow.createCell(3).setCellValue("Chinese Meaning");
        titleRow.createCell(4).setCellValue("Example Sentence");
        titleRow.createCell(5).setCellValue("Example Translation");

        // 数据库查询
        int rowNum = 1;
        try (Connection conn = DriverManager.getConnection(url, user, password);
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery("SELECT * FROM EnglishWords")) {

            while (rs.next()) {
                Row row = sheet.createRow(rowNum++);
                row.createCell(0).setCellValue(rs.getInt("id"));
                row.createCell(1).setCellValue(rs.getString("word"));
                row.createCell(2).setCellValue(rs.getString("phonetic"));
                row.createCell(3).setCellValue(rs.getString("chinese_meaning"));
                row.createCell(4).setCellValue(rs.getString("example_sentence"));
                row.createCell(5).setCellValue(rs.getString("example_translation"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 写入Excel文件
        try (FileOutputStream outputStream = new FileOutputStream("EnglishWords.xlsx")) {
            workbook.write(outputStream);
        } finally {
            // 关闭工作簿资源
            workbook.close();
        }
    }

    public static void main(String[] args) {
        try {
            exportDataToExcel();
            System.out.println("数据导出成功,文件保存为 EnglishWords.xlsx");
        } catch (IOException e) {
            System.out.println("导出数据时发生错误:" + e.getMessage());
        }
    }
}


```

这段代码首先创建了一个Excel工作簿和工作表,然后从数据库中查询数据并填充到工作表中。最后,它将工作簿写入到一个名为`EnglishWords.xlsx`的文件中。

请注意,你需要将数据库连接信息(URL、用户名、密码)替换为你自己的信息。此外,Apache POI的版本号也需要根据你使用的版本进行替换。

在运行这段代码之前,请确保你已经添加了Apache POI库到你的项目中,并且你的数据库中确实存在`EnglishWords`表和相应的数据。

---------------------------------------------------------------------------------------------------------------------------------

要将Excel文件的数据写入MySQL数据库,你可以使用Java的一些库,如Apache POI来读取Excel文件,然后使用JDBC来执行插入数据库的操作。以下是一个示例代码,演示如何实现这个功能。

首先,确保你的`pom.xml`文件中包含了Apache POI和MySQL Connector的依赖:

```xml

<!-- Apache POI -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>版本号</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>版本号</version>
</dependency>

<!-- MySQL Connector -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>版本号</version>
</dependency>


```

然后,你可以使用以下Java代码来实现将数据从Excel文件写入MySQL数据库的功能:

```java

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class ImportToMySQL {

    public static void importExcelToMySQL(String excelFilePath) {
        // 数据库连接信息
        String url = "jdbc:mysql://localhost:3306/你的数据库名";
        String user = "用户名";
        String password = "密码";
        String tableName = "EnglishWords";

        // 加载Excel文件
        Workbook workbook;
        try (FileInputStream fileInputStream = new FileInputStream(new File(excelFilePath))) {
            workbook = new XSSFWorkbook(fileInputStream);
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }

        // 获取工作表
        Sheet sheet = workbook.getSheetAt(0);

        // 准备JDBC插入语句
        String sql = "INSERT INTO " + tableName + " (word, phonetic, chinese_meaning, example_sentence, example_translation) VALUES (?, ?, ?, ?, ?)";
        try (Connection conn = DriverManager.getConnection(url, user, password);
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            // 跳过标题行,从第一行数据开始
            for (int rowIndex = 1; rowIndex <= sheet.getLastRowNum(); rowIndex++) {
                Row row = sheet.getRow(rowIndex);
                if (row == null) {
                    continue;
                }

                // 读取单元格数据
                Cell wordCell = row.getCell(1);
                Cell phoneticCell = row.getCell(2);
                Cell chineseMeaningCell = row.getCell(3);
                Cell exampleSentenceCell = row.getCell(4);
                Cell exampleTranslationCell = row.getCell(5);

                // 设置预处理语句的参数
                pstmt.setString(1, wordCell.getStringCellValue());
                pstmt.setString(2, phoneticCell.getStringCellValue());
                pstmt.setString(3, chineseMeaningCell.getStringCellValue());
                pstmt.setString(4, exampleSentenceCell.getStringCellValue());
                pstmt.setString(5, exampleTranslationCell.getStringCellValue());

                // 执行插入操作
                pstmt.executeUpdate();
            }

            System.out.println("数据导入成功");

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (workbook != null) {
                try {
                    workbook.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        String excelFilePath = "EnglishWords.xlsx"; // Excel文件路径
        importExcelToMySQL(excelFilePath);
    }
}


```

这段代码首先加载Excel文件,然后读取工作表中的数据。对于工作表中的每一行数据,它都会准备一个JDBC的`PreparedStatement`来执行插入操作,并将Excel中的数据作为参数传递给这个语句。最后,它会执行插入操作,并将数据写入到MySQL数据库中。

请注意,你需要将数据库连接信息(URL、用户名、密码)和Excel文件路径替换为你自己的信息。此外,Apache POI和MySQL Connector的版本号也需要根据你使用的版本进行替换。

在运行这段代码之前,请确保你已经添加了Apache POI和MySQL Connector库到你的项目中,并且你的Excel文件`EnglishWords.xlsx`中确实存在数据。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值