如何修改将.xls导出到xssfworkbook

时间:2019-07-17 18:30:00

标签: java excel jsp apache-poi

我已经使用HSSFWorkbook导入.xls文件,但是我需要使用XSSFWorkbook导入.xls和.xlsx文件。我需要将hssf工作表和xssf工作表都转换为MySQL数据库。 有人请帮助我提供一些代码,以将.xls和.xlsx工作表导入MySQL数据库。我已经尝试过导入一些代码,但是如果我们使用HSSFWorkbook,则在该代码中将上传.xls文件,但是当我更改为XSSFWorkbook时,却在XSSFWorkbook声明中显示了错误。 >

try {
    String company, currentPayor, dateofservice, balance, patient_name, led_age;

    Class.forName("com.mysql.jdbc.Driver");
    Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/technosoftproj", "root", "mahi777777");
    con.setAutoCommit(false);
    PreparedStatement pstm = null;
    FileInputStream input = new FileInputStream(new File("C://Users//Nandana//Desktop//tasks.xlsx"));
    //POIFSFileSystem fs = new POIFSFileSystem( input ); //creating a new poi reference to the given excel file
    XSSFWorkbook wb = new XSSFWorkbook(input);
    XSSFSheet sheet = wb.getSheetAt(0);
    Row row;
    Statement st = con.createStatement();
    for (int i = 1; i <= sheet.getLastRowNum(); i++) { //points to the starting of excel i.e excel first row
        row = (Row) sheet.getRow(i); //sheet number

        if (row.getCell(0) == null) {
            company = "0";
        } //suppose excel cell is empty then its set to 0 the variable
        else company = row.getCell(0).toString(); //else copies cell data to name variable

        if (row.getCell(1) == null) {
            currentPayor = "0";
        } else currentPayor = row.getCell(1).toString();

        if (row.getCell(2) == null) {
            dateofservice = "0";
        } else dateofservice = row.getCell(2).toString();

        if (row.getCell(2) == null) {
            balance = "0";
        } else balance = row.getCell(2).toString();

        if (row.getCell(2) == null) {
            patient_name = "0";
        } else patient_name = row.getCell(2).toString();

        if (row.getCell(2) == null) {
            led_age = "0";
        } else led_age = row.getCell(2).toString();

        String sq = "INSERT INTO tasks(company,currentPayor,dateofservice,balance,patient_name,led_age) VALUES('" + company + "','" + currentPayor + "','" + dateofservice + "','" + balance + "','" + patient_name + "','" + led_age + "')";

        pstm = (PreparedStatement) con.prepareStatement(sq); //here we are using prepared statement because we are calling this statement for each row
        pstm.execute();

        System.out.println("Import rows " + i);
    }

0 个答案:

没有答案