使用Java将.csv或.xlsx文件导入mysql DB?

时间:2017-09-07 13:32:28

标签: java mysql excel csv intellij-idea

是的,听起来像是重复的。

我正在Intellij上练习Java的abit,并尝试编写一个程序将.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)

我的代码:

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) {
    }
}

}

非常感谢有关如何调整此代码以导入.csv或xlsx文件的任何建议。

4 个答案:

答案 0 :(得分:2)

您应该按原样使用PreparedStatement:

String sql = "INSERT INTO testtable (text, price) VALUES(?, ?)";       
pstm = (PreparedStatement) con.prepareStatement(sql);
pstm.setString(1, text);
pstm.setInteger(2, text)
pstm.execute();

我想这不起作用,因为text中有一些标点符号。 它也容易进行SQL注入。

此外,您应该使用try-with-resourcesfinally关闭可关闭的对象(如果您坚持使用java版本之前的版本7),就像在此处完成一样:

https://stackoverflow.com/a/26516076/3323777

编辑:啊,是的,像亚历克斯所说的那个空陷阱。也不要这样做。

<强> EDIT2

  

Apache POI从未设计为调用CSV文件。

https://stackoverflow.com/a/1087984/3323777

Apache有另一个CSV项目:

http://commons.apache.org/proper/commons-csv/

答案 1 :(得分:0)

你看到&#34;导入行&#34;证明你确实要导入一些行的消息?

也没有看到任何错误的原因可能是&#34; catch&#34;块无效。在里面添加任何输出并观察新结果,即

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

答案 2 :(得分:0)

调整来自.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) {
}

}

答案 3 :(得分:0)

尝试使用&#39; poi-ooxml&#39;对于创建Workbook对象,其gradle依赖关系签名如下所示:

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);