繁体   English   中英

如何使用java POI从excel表中插入数据库读取?

[英]How to insert into database reading from excel sheet using java POI?

我正在使用 java POI 从 excel 工作表中读取值并需要插入到数据库中。我有来自 excel 工作表的字符串、数字和日期值以及第一个字段是列标题。

public class SimpleExcelReadExample {
  static Connection con1 = null;
  static Connection con3 = null;
  static PreparedStatement preparedstatement = null;
  static ResultSet resultset = null;
  int j = 0;

  public static void main(String[] args) {

        String fileName = "D:/Excel/Report.xls";
        Cleartables.table_daily_report();
        Vector dataHolder = read(fileName);
        saveToDatabase(dataHolder);
  }

  public static Vector read(String fileName) {
        Vector cellVectorHolder = new Vector();
        try {
              FileInputStream myInput = new FileInputStream(fileName);
              POIFSFileSystem myFileSystem = new POIFSFileSystem(myInput);
              HSSFWorkbook myWorkBook = new HSSFWorkbook(myFileSystem);
              HSSFSheet mySheet = myWorkBook.getSheetAt(0);
              Iterator rowIter = mySheet.rowIterator();
              while (rowIter.hasNext()) {
                    HSSFRow myRow = (HSSFRow) rowIter.next();
                    Iterator cellIter = myRow.cellIterator();
                    Vector cellStoreVector = new Vector();
                    while (cellIter.hasNext()) {
                          HSSFCell myCell = (HSSFCell) cellIter.next();
                          //System.out.println("read method"+myCell);
                          cellStoreVector.addElement(myCell);
                    }
                    cellVectorHolder.addElement(cellStoreVector);
              }
        } catch (Exception e) {
              e.printStackTrace();
        }
        return cellVectorHolder;
  }

  private static void saveToDatabase(Vector dataHolder)
  {

                    for (int i=0;i<dataHolder.size(); i++)
                    {
                       Vector cellStoreVector=(Vector)dataHolder.elementAt(i);
                       for (int j=0; j < cellStoreVector.size();j++)
                    {
                             System.out.println("show.....");
                            HSSFCell myCell = (HSSFCell)cellStoreVector.elementAt(j);

                           Please help me here....How to get the each column values  ?
                    }
try {

        FileInputStream file = new FileInputStream(new File("E://Imp/Details.xlsx"));
        XSSFWorkbook workbook = new XSSFWorkbook(file);
        XSSFSheet sheet = workbook.getSheetAt(0);
        Iterator<Row> rowIterator = sheet.iterator();
        rowIterator.next();
        while(rowIterator.hasNext())
        {
            Row row = rowIterator.next();
            //For each row, iterate through each columns
            Iterator<Cell> cellIterator = row.cellIterator();

            while(cellIterator.hasNext())
            {
                Cell cell = cellIterator.next();
                //This will change all Cell Types to String
                cell.setCellType(Cell.CELL_TYPE_STRING);
                switch(cell.getCellType()) 
                {
                    case Cell.CELL_TYPE_BOOLEAN:
                        System.out.println("boolean===>>>"+cell.getBooleanCellValue() + "\t");
                        break;
                    case Cell.CELL_TYPE_NUMERIC:

                        break;
                    case Cell.CELL_TYPE_STRING:

                       list.add(cell.getStringCellValue());

                                                 break;
                }


            }
            name=row.getCell(0).getStringCellValue();
            empid=row.getCell(1).getStringCellValue();
            add=row.getCell(2).getStringCellValue();
            mobile=row.getCell(3).getStringCellValue();
            System.out.println(name+empid+add+mobile);
            ex.InsertRowInDB(name,empid,add,mobile);
            System.out.println("");


        }
        file.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
  }
    public void InsertRowInDB(String name,String empid,String add,String mobile) throws SQLException{

        Statement stmt=db.con.createStatement();
        PreparedStatement ps=null;
        String sql="Insert into Employee(Name,EmployeeId,Address,ContactInfo) values(?,?,?,?)";
        ps=db.con.prepareStatement(sql);
        ps.setString(1, name);
        ps.setString(2, empid);
        ps.setString(3, add);
        ps.setString(4, mobile);
    ps.executeUpdate();
    System.out.println("Values Inserted Successfully");
    }
}

试试这个:

尝试 {

        String jdbc_insert_sql = "INSERT INTO TBL_PUNETORET"
                + "( NUMRI_PERSONAL, EMRI_MBIEMRI,DATELINDJA,ADRESA,TELEFONI,DATA_PUNSIMIT,DATA_LARGIMIT,NJESIA,POZITA,TELEFONI_P,EMAIL,PERSHKRIMI,PUNTORI,REKOMANDUAR) "
                + "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        Class.forName("oracle.jdbc.driver.OracleDriver");

        PreparedStatement preStatement = con.prepareStatement(jdbc_insert_sql);
        con.setAutoCommit(false);

        FileInputStream input = new FileInputStream(filename);
        POIFSFileSystem fs = null;
        try {
            fs = new POIFSFileSystem(input);
        } catch (IOException ex) {
            Logger.getLogger(PunetoretForm.class.getName()).log(Level.SEVERE, null, ex);
        }
        HSSFWorkbook wb = new HSSFWorkbook(fs);
        HSSFSheet sheet = wb.getSheetAt(0);
        Row row;
        for (int i = 1; i <= sheet.getLastRowNum(); i++) {
            row = sheet.getRow(i);
            int numripersonal = (int) (row.getCell(0).getNumericCellValue());
            //String numripersonal =  row.getCell(0).getStringCellValue(); 
            String emri = row.getCell(1).getStringCellValue();
            Date datelindja = row.getCell(4).getDateCellValue();
            DateFormat df = new SimpleDateFormat("dd/MMM/yyyy");
            String reportDate = df.format(datelindja);
            df.parse(reportDate);
            String adresa = row.getCell(5).getStringCellValue();
            int telefoni = (int) (row.getCell(6).getNumericCellValue());
            //String telefoni = row.getCell(4).getStringCellValue();
            Date datap = row.getCell(7).getDateCellValue();
            df = new SimpleDateFormat("dd/MMM/yyyy");
            String reportDatap = df.format(datap);
            df.parse(reportDatap);

            Date datal = row.getCell(8).getDateCellValue();
            String ss = null;
            if (datal != null) {
                df = new SimpleDateFormat("dd/MMM/yyyy");
                ss = df.format(datal);
                df.parse(ss);

            }

            String njesia = row.getCell(9).getStringCellValue();
            String pozita = row.getCell(10).getStringCellValue();
            int telp = (int) (row.getCell(11).getNumericCellValue());
            if (telp == 0) {
                String s = String.valueOf(telp);
                s = "Ska numer";
            }
            //String telp = row.getCell(9).getStringCellValue();
            String email = row.getCell(12).getStringCellValue();
            String pershkrimi = row.getCell(13).getStringCellValue();
            String punetori = row.getCell(14).getStringCellValue();
            String rekomanduar = row.getCell(15).getStringCellValue();
            if (datal == null) {
                String sql = "INSERT INTO TBL_PUNETORET ( NUMRI_PERSONAL, EMRI_MBIEMRI,DATELINDJA,ADRESA,TELEFONI,DATA_PUNSIMIT,DATA_LARGIMIT,NJESIA,POZITA,TELEFONI_P,EMAIL,PERSHKRIMI,PUNTORI,REKOMANDUAR) "
                        + "VALUES('" + numripersonal + "','" + emri + "','" + reportDate + "','" + adresa + "','" + telefoni + "','" + reportDatap + "'," + datal + ",'" + njesia + "','" + pozita + "','" + telp + "','" + email + "','" + pershkrimi + "','" + rekomanduar + "','" + punetori + "')";
                preStatement = (PreparedStatement) con.prepareStatement(sql);
                preStatement.execute();
            }

这是我为相同操作编写的代码。 请注意,我还创建了一个 Employee java 类,其中包含所有这 4 个属性:id、name、gender 工资及其 getter-setter。

package com.hibernate.poiex2;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Iterator;
import java.util.Properties;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

/**
 *
 * @author nidhi
 */
public class POIex2 {

    XSSFRow row;
    Employee e = new Employee();

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

        String fileName = "/home/nidhi/Downloads/Employees.xlsx";
        POIex2 poIex2 = new POIex2();
        poIex2.readFile(fileName);
    }

    public void readFile(String fileName) throws FileNotFoundException, IOException {
        FileInputStream fis;
        try {
            System.out.println("-------------------------------READING THE SPREADSHEET-------------------------------------");
            fis = new FileInputStream(fileName);
            XSSFWorkbook workbookRead = new XSSFWorkbook(fis);
            XSSFSheet spreadsheetRead = workbookRead.getSheetAt(0);

            Iterator< Row> rowIterator = spreadsheetRead.iterator();
            while (rowIterator.hasNext()) {
                row = (XSSFRow) rowIterator.next();
                Iterator< Cell> cellIterator = row.cellIterator();

                while (cellIterator.hasNext()) {
                    Cell cell = cellIterator.next();
                    cell.setCellType(CellType.STRING);
                    switch (cell.getColumnIndex()) {
                        case 0:
                            System.out.print(
                                    cell.getStringCellValue() + " \t\t");
                            break;
                        case 1:
                            System.out.print(
                                    cell.getStringCellValue() + " \t\t");
                            break;
                        case 2:
                            System.out.print(
                                    cell.getStringCellValue() + " \t\t");
                            break;
                        case 3:
                            System.out.print(
                                    cell.getStringCellValue() + " \t\t");
                            break;
                        case 4:
                            System.out.print(
                                    cell.getStringCellValue() + " \t\t");
                            break;
                    }
                }
                System.out.println();
                e.empId = Integer.parseInt(row.getCell(0).getStringCellValue());
                e.empName = row.getCell(1).getStringCellValue();
                e.gender = row.getCell(2).getStringCellValue();
                e.salary = row.getCell(3).getStringCellValue();

                InsertRowInDB(e.empId, e.empName, e.gender, e.salary);
            }
            System.out.println("Values Inserted Successfully");

            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void InsertRowInDB(int empId, String empName, String gender, String salary) {

        Float salaryDB = Float.parseFloat(salary);
        try {

            Properties properties = new Properties();
            properties.setProperty("user", "root");
            properties.setProperty("password", "root");
            properties.setProperty("useSSL", "false");
            properties.setProperty("autoReconnect", "true");

            Class.forName("com.mysql.jdbc.Driver");
            Connection connect = DriverManager.getConnection("jdbc:mysql://localhost:3306/Attendance", properties);
            Statement stmt = connect.createStatement();
            PreparedStatement ps = null;
            String sql = "INSERT INTO `Attendance`.`Employee_Master`\n"
                    + "(`EmployeeId`,\n"
                    + "`EmployeeName`,\n"
                    + "`Gender`,\n"
                    + "`Salary`)\n"
                    + "VALUES(?,?,?,?)";
            ps = connect.prepareStatement(sql);
            ps.setInt(1, empId);
            ps.setString(2, empName);
            ps.setString(3, gender);
            ps.setFloat(4, salaryDB);
            ps.executeUpdate();
            connect.close();
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
    }
}

试试这个

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;

import com.mani.beans.Student;

public class ReadDataFromExcel {
    public static void main(String args[]) throws IOException {
        SessionFactory sf = new AnnotationConfiguration().configure("com/mani/resources/hibernate.cfg.xml").buildSessionFactory();
        Session session = sf.openSession();
        FileInputStream file = new FileInputStream(new File("C:/Users/mani/Desktop/data.xlsx")); 
        XSSFWorkbook workbook = new XSSFWorkbook(file); 
        XSSFSheet sheet = workbook.getSheetAt(1); 
        Row row;
        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


                String id;
                if( row.getCell(0)==null) { id = "0"; }
                else id= row.getCell(0).toString();

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

                   String address;
                if( row.getCell(2)==null) { address = "null";   }
                   else  address   = row.getCell(2).toString();
        Transaction t = session.beginTransaction();
        Student std = new Student();
        std.setId(Double.parseDouble(id));
        std.setName(name);
        std.setAddress(address);
        System.out.println(std.getId()+" "+std.getName()+" "+std.getAddress());
        session.saveOrUpdate(std);
        t.commit();     
        }
        file.close();
    }


}`

Excel 文件插入数据库。 这个对我有用。

导入的jar文件:

  • poi-ooxml 3.5-beta5
  • xmlbeans
  • apache-logging-log4j
  • dom4j-1.5
  • POI 3.10.1
  • POI 3.14
  • poi ooxml-schema 3.7-beta5

不要忘记导入数据库jar文件。

希望它会帮助你。

public class ExcelToDatabase {
 public static void main(String[] args) {
  try {
   String filename = "exceldatabase.xlsx";
   try (FileInputStream file = new FileInputStream(new File(filename))) {
    Workbook workbook = WorkbookFactory.create(file);
    Class.forName("com.mysql.jdbc.Driver");
    Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");

    String jdbc_insert_sql = "INSERT INTO employee" + "VALUES(?,?,?)";
    PreparedStatement preStatement = con.prepareStatement(jdbc_insert_sql);

    Sheet sheet = workbook.getSheetAt(0);
    Row row;
    System.out.println("last row number is=========" + sheet.getLastRowNum());
    for (int i = 1; i <= sheet.getLastRowNum(); i++) {
     row = sheet.getRow(i);
     int empId = (int)(row.getCell(0).getNumericCellValue());
     String empName = row.getCell(1).getStringCellValue();
     String empEmail = row.getCell(2).getStringCellValue();

     String sql = "insert into employee " + "values('" + empId + "','" + empName + "','" + empEmail + "')";
     preStatement = (PreparedStatement) con.prepareStatement(sql);
     preStatement.execute();
     System.out.println("Records inserted.........." + i);

    }
    System.out.println("");
   }
  } catch (Exception e) {}
 }
}

如何从excel表中读取数据并插入到java中的数据库表中

if (fileName.endsWith(".xls")) {

                CustomerVo customerVo = new CustomerVo();//your vo 
                File myFile = new File("file location" + fileName);
                FileInputStream fis = new FileInputStream(myFile);

                // Finds the workbook instance for XLSX file

                org.apache.poi.ss.usermodel.Workbook workbook = null;
                try {
                    workbook = WorkbookFactory.create(fis);
                } catch (InvalidFormatException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                Row row = null;
                // Return first sheet from the XLSX workbook
                org.apache.poi.ss.usermodel.Sheet sheet = workbook.getSheetAt(0);

                // Get iterator to all the rows in current sheet
                Iterator<Row> rowIterator = sheet.iterator();
                int i = 0;
                // Traversing over each row of XLSX file
                while (rowIterator.hasNext()) {

                    row = rowIterator.next();
                    Iterator<Cell> cellIterator = row.cellIterator();
                    if (i != 0) {

                        while (cellIterator.hasNext()) {
                            Cell cell = cellIterator.next();
                            if (i != 0) {
                                switch (cell.getCellType()) {
                                case Cell.CELL_TYPE_STRING:
                                    System.out.print(cell.getStringCellValue());
                                    customerVo.setName(row.getCell(1).getStringCellValue());
                                    customerVo.setSex(row.getCell(2).getStringCellValue());

                                    DateFormat formatter = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
                                    Date date;
                                    try {
                                        date = (Date) formatter.parse(row.getCell(3).getStringCellValue());
                                        customerVo.setDob(date);
                                    } catch (ParseException e) {
                                        // TODO Auto-generated catch block
                                        e.printStackTrace();
                                    }

                                    customerVo.setEmail(row.getCell(4).getStringCellValue());
                                    customerVo.setAddress(row.getCell(6).getStringCellValue());
                                    customerVo.setCity(row.getCell(8).getStringCellValue());
                                    customerVo.setState(row.getCell(9).getStringCellValue());
                                    break;
                                case Cell.CELL_TYPE_BOOLEAN:
                                    System.out.print(cell.getBooleanCellValue());
                                    break;
                                case Cell.CELL_TYPE_NUMERIC:
                                    System.out.print(cell.getNumericCellValue());
                                    customerVo.setAccountnumber((int) row.getCell(0).getNumericCellValue());
                                    customerVo.setPincode((int) row.getCell(7).getNumericCellValue());
                                    customerVo.setBalance((int) row.getCell(10).getNumericCellValue());
                                    customerVo.setMobile((long) row.getCell(5).getNumericCellValue());
                                    break;
                                }
                                System.out.print(" - ");
                            }
                            i++;

                        }
                        System.out.println(customerVo);//your data store in the object
                        fileUploadService.customerFile(customerVo);//this method using mvc service to dao impl 
                    }
                    i++;
                }
            }

// 用于将文件存储到数据库

@Repository 公共类 FileUploadDAOImpl 实现了 FIleUploadDAO {

@Autowired
private DataSource dataSource;


@Override
public CustomerVo customerFile(CustomerVo customerVo) {

    String query = "insert into file_upload_table(name,sex,dob,email,mobile,address,pincode,city,state,balance,account_number)"
            + "values(?,?,?,?,?,?,?,?,?,?,?)";

    Connection connection = null;
    try {
        connection = dataSource.getConnection();

        Date oldDate = new Date(customerVo.getDob().getTime());

        java.sql.PreparedStatement ps = null;
        java.sql.ResultSet rs = null;
        try {
            ps = connection.prepareStatement(query);
            // ps.setLong(1, customerVO.getAccountNo());
            ps.setString(1, customerVo.getName());
            ps.setString(2, customerVo.getSex());
            ps.setDate(3,oldDate);
            ps.setString(4, customerVo.getEmail());
            ps.setLong(5, customerVo.getMobile());
            ps.setString(6, customerVo.getAddress());
            ps.setLong(7, customerVo.getPincode());
            ps.setString(8, customerVo.getCity());
            ps.setString(9, customerVo.getState());
            ps.setLong(10, customerVo.getBalance());
            ps.setLong(11, customerVo.getAccountnumber());
            ps.executeUpdate();

        } catch (SQLException e) {
            // TODO: handle exception
            e.printStackTrace();
        }


    } catch (SQLException e) {

        // TODO Auto-generated catch block

        e.printStackTrace();
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM