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();
}
}
}
导入必要的库:
java.io
:用于文件输入输出操作。java.sql
:用于数据库连接和操作。org.apache.poi.xwpf.usermodel
:用于读取Word文档的内容。主方法 (main
):
DriverManager.getConnection
方法建立数据库连接。FileInputStream
读取Word文档。XWPFDocument
类解析Word文档,并将内容逐段读取到一个StringBuilder
中。PreparedStatement
来执行SQL插入语句。IOException
和SQLException
异常。注意事项:
poi-ooxml
)到你的项目依赖中。wordFilePath
、jdbcUrl
、dbUser
和dbPassword
以匹配你的实际情况。documents
需要预先创建,并包含一个名为content
的字段。上一篇:java 时间转字符串
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站