java - 如何使用java将excel数据(.xlsx)插入mysql数据库?
问题描述
是的,这听起来像是重复的。
我正在 Netbeans 上练习一点 Java,并尝试编写一个程序来将 .xlsx excel 文件导入 MySQL 数据库。重复的问题,是的,但是在互联网上拖网并没有带来太多收益。
package practice;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.*;
public class File2MySqlDB {
public static void main(String[] args) throws Exception {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = null;
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/databasename", "root", "root");
con.setAutoCommit(false);
PreparedStatement pstm = null;
FileInputStream input = new FileInputStream("C:\\Users\\user\\Desktop\\Student.xlsx");
POIFSFileSystem fs = new POIFSFileSystem(input);
Workbook workbook;
workbook = WorkbookFactory.create(fs);
Sheet sheet = workbook.getSheetAt(0);
Row row;
for (int i = 1; i <= sheet.getLastRowNum(); i++) {
row = (Row) sheet.getRow(i);
String Name = row.getCell(0).getStringCellValue();
String Enrolled = row.getCell(1).getStringCellValue();
String Progress = row.getCell(2).getStringCellValue();
String sql = "INSERT INTO Student (Name, Enrolled,Progress) VALUES('" + Name + "','" + Enrolled + "', '"+Progress+"')";
pstm = (PreparedStatement) con.prepareStatement(sql);
pstm.setString(1, Name);
pstm.setString(2, Enrolled);
pstm.setString(3, Progress);
pstm.execute();
System.out.println("Import rows " + i);
}
con.commit();
pstm.close();
con.close();
input.close();
System.out.println("Success import excel to mysql table");
} catch (IOException e) {e.printStackTrace();}
}
}
提示:我正在使用 apipoi-4.1.1.jar
我得到以下错误
Exception in thread "main" org.apache.poi.poifs.filesystem.OfficeXmlFileException: The supplied data appears to be in the Office 2007+ XML. You are calling the part of POI that deals with OLE2 Office Documents. You need to call a different part of POI to process this data (eg XSSF instead of HSSF)
at org.apache.poi.poifs.storage.HeaderBlock.<init>(HeaderBlock.java:130)
at org.apache.poi.poifs.storage.HeaderBlock.<init>(HeaderBlock.java:117)
at org.apache.poi.poifs.filesystem.POIFSFileSystem.<init>(POIFSFileSystem.java:294)
at practice.File2MySqlDB.main(File2MySqlDB.java:20)
解决方案
推荐阅读
- c++ - 链表节点类 C++ 中的清除函数
- azure - 如何为 Azure Linux 服务 Web 应用设置加密
- javascript - 如何在不重新加载页面的情况下提交 asp.net core razor pages 表单
- java - 打破 hasNext 循环
- python - 在类中定义函数(而不是方法)的最佳方法是什么?
- apache-spark - AWS EMR 上的 Spark 作业的 CPU 利用率非常低
- python - 无法在我的 python IDLE 中导入 pyperclip,但能够从命令提示符导入
- jquery - 循环通过文件客户端进行文件上传控制
- git - 如何在 Git 触发器运行之前检查第三方网站的更新?
- java - 我正在使用条带支付 java 实现。没有此类费用的条纹退款存在成功付款的例外情况