Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

java读取word文档存到数据库

作者:寡欢—   发布日期:2025-09-14   浏览:26

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;

public class WordToDatabase {

    public static void main(String[] args) {
        String wordFilePath = "path/to/your/document.docx";
        String jdbcUrl = "jdbc:mysql://localhost:3306/your_database";
        String dbUser = "your_username";
        String dbPassword = "your_password";

        try (Connection conn = DriverManager.getConnection(jdbcUrl, dbUser, dbPassword);
             FileInputStream fis = new FileInputStream(wordFilePath)) {

            // Read Word Document
            XWPFDocument document = new FileInputStream(fis);
            StringBuilder contentBuilder = new StringBuilder();
            for (XWPFParagraph paragraph : document.getParagraphs()) {
                contentBuilder.append(paragraph.getText()).append("\n");
            }
            String documentContent = contentBuilder.toString();

            // Insert into Database
            String sql = "INSERT INTO documents (content) VALUES (?)";
            try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
                pstmt.setString(1, documentContent);
                pstmt.executeUpdate();
            }

            System.out.println("Document content has been successfully inserted into the database.");

        } catch (IOException | SQLException e) {
            e.printStackTrace();
        }
    }
}

解释说明

  1. 导入必要的库

    • java.io:用于文件输入输出操作。
    • java.sql:用于数据库连接和操作。
    • org.apache.poi.xwpf.usermodel:用于读取Word文档的内容。
  2. 主方法 (main)

    • 设置Word文档的路径、数据库的URL、用户名和密码。
    • 使用DriverManager.getConnection方法建立数据库连接。
    • 使用FileInputStream读取Word文档。
    • 使用XWPFDocument类解析Word文档,并将内容逐段读取到一个StringBuilder中。
    • 将构建好的文档内容插入到数据库中,使用PreparedStatement来执行SQL插入语句。
    • 捕获并处理可能的IOExceptionSQLException异常。
  3. 注意事项

    • 确保你已经添加了Apache POI库(如poi-ooxml)到你的项目依赖中。
    • 修改wordFilePathjdbcUrldbUserdbPassword以匹配你的实际情况。
    • 数据库表documents需要预先创建,并包含一个名为content的字段。

上一篇:java 时间转字符串

下一篇:java判断字符串不为空和null

大家都在看

java连接数据库的代码

java djl

ubuntu 卸载java

java读取excel中的图片

java新建

java sort用法

java collections.sort

java file类的方法

java发送qq邮件

java 判断

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站