Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/58.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Java将.csv或.xlsx文件导入mysql数据库?_Java_Mysql_Excel_Csv_Intellij Idea - Fatal编程技术网

使用Java将.csv或.xlsx文件导入mysql数据库?

使用Java将.csv或.xlsx文件导入mysql数据库?,java,mysql,excel,csv,intellij-idea,Java,Mysql,Excel,Csv,Intellij Idea,是的,听起来像是复制品 我正在Intellij上练习Java,并尝试编写一个程序将.xls excel文件导入mysql数据库。重复的问题,是的,但拖网上网并没有产生多大效果 我下面的代码目前可以完美地导入任何xls文件。不幸的是,它对.csv文件和xlsx文件都没有任何作用 尝试使用.csv文件时,会引发以下错误: Invalid header signature; read 0x6972702C74786574, expected 0xE11AB1A1E011CFD0 - Your file

是的,听起来像是复制品

我正在Intellij上练习Java,并尝试编写一个程序将.xls excel文件导入mysql数据库。重复的问题,是的,但拖网上网并没有产生多大效果

我下面的代码目前可以完美地导入任何xls文件。不幸的是,它对.csv文件和xlsx文件都没有任何作用

尝试使用.csv文件时,会引发以下错误:

Invalid header signature; read 0x6972702C74786574, expected 0xE11AB1A1E011CFD0 - Your file appears not to be a valid OLE2 document
使用xlsx文件时,会将以下内容作为错误抛出:

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:152)
at org.apache.poi.poifs.storage.HeaderBlock.<init>(HeaderBlock.java:140)
at org.apache.poi.poifs.filesystem.NPOIFSFileSystem.<init>(NPOIFSFileSystem.java:302)
at org.apache.poi.poifs.filesystem.POIFSFileSystem.<init>(POIFSFileSystem.java:85)
at FileExport.main(FileExport.java:21)
线程“main”org.apache.poi.poifs.filesystem.OfficeXmlFileException中的异常:提供的数据似乎位于Office 2007+XML中。您正在调用POI中处理OLE2 Office文档的部分。您需要调用POI的不同部分来处理此数据(例如XSSF而不是HSSF) 位于org.apache.poi.poifs.storage.HeaderBlock(HeaderBlock.java:152) 位于org.apache.poi.poifs.storage.HeaderBlock(HeaderBlock.java:140) 位于org.apache.poi.poifs.filesystem.NPOIFSFileSystem.(NPOIFSFileSystem.java:302) 位于org.apache.poi.poifs.filesystem.poifsffilesystem.(poifsffilesystem.java:85) 在FileExport.main(FileExport.java:21) 我的代码:

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 FileExport {

public static void main(String[] args) throws Exception {

    try {

        Class forName = Class.forName("com.mysql.jdbc.Driver");
        Connection con = null;
        con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useSSL=false", "root", "root");
        con.setAutoCommit(false);
        PreparedStatement pstm = null;
        FileInputStream input = new FileInputStream("/Users/User/Desktop/Email/Test.xls");
        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 text = row.getCell(0).getStringCellValue();
            int price = (int) row.getCell(1).getNumericCellValue();


            String sql = "INSERT INTO testtable (text, price) VALUES('" + text + "','" + price + "')";
            pstm = (PreparedStatement) con.prepareStatement(sql);
            pstm.setString(1, text);
            pstm.setInt(2, price);
            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) {
    }
}
import java.io.FileInputStream;
导入java.io.IOException;
导入java.sql.Connection;
导入java.sql.DriverManager;
导入java.sql.PreparedStatement;
导入org.apache.poi.poifs.filesystem.poifsfsystem;
导入org.apache.poi.ss.usermodel.*;
公共类文件导出{
公共静态void main(字符串[]args)引发异常{
试一试{
Class-forName=Class.forName(“com.mysql.jdbc.Driver”);
连接con=null;
con=DriverManager.getConnection(“jdbc:mysql://localhost:3306/test?useSSL=false“,”根“,”根“);
con.setAutoCommit(假);
PreparedStatement pstm=null;
FileInputStream输入=新的FileInputStream(“/Users/User/Desktop/Email/Test.xls”);
POIFSFISTEM fs=新的POIFSFISTEM(输入);
工作手册;
工作簿=WorkbookFactory.create(fs);
工作表=工作簿。getSheetAt(0);
行行;
对于(int i=1;i您是否看到“导入行”消息,这些消息证明您确实有一些行要导入

此外,没有看到任何错误的原因可能是“catch”块不起任何作用

 System.out.println(e.getMessage());
您是否看到“导入行”消息,这些消息证明您确实有一些行要导入

此外,没有看到任何错误的原因可能是“catch”块不起任何作用

 System.out.println(e.getMessage());

您应该使用PreparedStatement,因为它用于:

String sql = "INSERT INTO testtable (text, price) VALUES(?, ?)";       
pstm = (PreparedStatement) con.prepareStatement(sql);
pstm.setString(1, text);
pstm.setInteger(2, text)
pstm.execute();
我猜它不起作用,因为你的
文本中有一些标点符号。
此外,它还易于SQL注入

此外,您还应使用
try with resources
finally
关闭可关闭对象(如果您坚持使用java版本7之前的版本),如下所示:

编辑:啊,是的,就像亚历克斯说的,空的捕捉块。也不要这样做

EDIT2

ApachePOI从未被设计为调用CSV文件

Apache上还有另一个CSV项目:


您应该使用PreparedStatement,因为它用于:

String sql = "INSERT INTO testtable (text, price) VALUES(?, ?)";       
pstm = (PreparedStatement) con.prepareStatement(sql);
pstm.setString(1, text);
pstm.setInteger(2, text)
pstm.execute();
我猜它不起作用,因为你的
文本中有一些标点符号。
此外,它还易于SQL注入

此外,您还应使用
try with resources
finally
关闭可关闭对象(如果您坚持使用java版本7之前的版本),如下所示:

编辑:啊,是的,就像亚历克斯说的,空的捕捉块。也不要这样做

EDIT2

ApachePOI从未被设计为调用CSV文件

Apache上还有另一个CSV项目:


调整为从.csv读取

public class FileExport {

public static void main(String[] args) throws Exception {

try {

    Class forName = Class.forName("com.mysql.jdbc.Driver");
    Connection con = null;
    con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useSSL=false", "root", "root");
    con.setAutoCommit(false);
    PreparedStatement pstm = null;
    FileInputStream input = new FileInputStream("/Users/User/Desktop/Email/Test.csv");
     BufferedReader reader = new BufferedReader(new InputStreamReader(input));
     String row = reader.readLine();
     String text = row.split(";")[0];
     String price = row.split(";")[1];
     reader.close();

        String sql = "INSERT INTO testtable (text, price) VALUES('" + text + "','" + price + "')";
        pstm = (PreparedStatement) con.prepareStatement(sql);
        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) {
}

}

调整为从.csv读取

public class FileExport {

public static void main(String[] args) throws Exception {

try {

    Class forName = Class.forName("com.mysql.jdbc.Driver");
    Connection con = null;
    con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useSSL=false", "root", "root");
    con.setAutoCommit(false);
    PreparedStatement pstm = null;
    FileInputStream input = new FileInputStream("/Users/User/Desktop/Email/Test.csv");
     BufferedReader reader = new BufferedReader(new InputStreamReader(input));
     String row = reader.readLine();
     String text = row.split(";")[0];
     String price = row.split(";")[1];
     reader.close();

        String sql = "INSERT INTO testtable (text, price) VALUES('" + text + "','" + price + "')";
        pstm = (PreparedStatement) con.prepareStatement(sql);
        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) {
}

}

尝试使用“poi ooxml”创建工作簿对象,其渐变依赖项签名如下所示:

compile group: 'org.apache.poi', name: 'poi-ooxml', version: '3.14'
下面的代码可能对您有所帮助

InputStream inputStream = new FileInputStream("/Users/User/Desktop/Email/Test.xls");
XSSFWorkbook wb = new XSSFWorkbook(inputStream);
XSSFSheet sheet = wb.getSheetAt(0);

尝试使用“poi ooxml”创建工作簿对象,其渐变依赖项签名如下所示:

compile group: 'org.apache.poi', name: 'poi-ooxml', version: '3.14'
下面的代码可能对您有所帮助

InputStream inputStream = new FileInputStream("/Users/User/Desktop/Email/Test.xls");
XSSFWorkbook wb = new XSSFWorkbook(inputStream);
XSSFSheet sheet = wb.getSheetAt(0);

您可以自己读取并解析文件,而无需使用POIFS。Parsing.csv非常简单。只需逐行读取文件,并在分隔符处拆分该行(它并不总是逗号).请原谅我的无知,但是你能解释一下解析和这个有什么区别吗?我在谷歌冒险中在线看到过它,但不能真正了解解析文件的实际功能。@Peterb废墟,这是一个错误的建议。CSV有很多边缘案例。而且它与问题没有太大关系。你可以阅读文件并用语法解析它我们自己,不使用POIFS.Parsing.csv非常简单。只需逐行读取文件,并在分隔符处拆分行(它并不总是逗号).请原谅我的无知,但你能解释一下解析和这个有什么区别吗?我在谷歌冒险中在线看到过它,但不能真正了解解析文件的实际功能。@Peterb废墟,这是一个错误的建议。CSV有很多边缘案例。而且它与问题没有太大关系。我按照你的建议做了,事实上错误是弹出的:无效的页眉签名;读取0x697202C77865 74,预期的0xE11AB1A1E011CFD0-您的文件似乎不是有效的OL2文档。我建议您考虑用其他解决方案替换POIFS。或者自己做。这是不是大问题?打开文件,逐行读取,用逗号分隔符分割每行。OU建议并且确实出现了这个错误:无效的头签名;读取0x697202C77865 74,预期0xE11AB1A1E011CFD0-您的文件看起来不是有效的OLL2文档,我建议您考虑用其他解决方案替换POIFS。