将Excel数据转换为MySql表


问题内容

我正在spring开发一个应用程序,并使用Eclipse作为IDE使其hibernate。

我想将Excel文件数据转换为MySql表。

我提到了以下链接。

http://www.coderanch.com/t/608700/JDBC/databases/import-data-excel-files-
database

有人可以给我发送有用的链接或简单的Java代码吗?


问题答案:

这是您阅读Excel文件并将其存储在集合对象中的方式

    import java.io.*;
    import java.util.Iterator;

    import org.apache.poi.ss.usermodel.Cell;
    import org.apache.poi.ss.usermodel.Row;
    import org.apache.poi.xssf.usermodel.XSSFSheet;
    import org.apache.poi.xssf.usermodel.XSSFWorkbook;

    public class ReadExcelFile {
        public static void main(String[] args) 
        {
            try {

                FileInputStream file = new FileInputStream(new File("C:/Users/hussain.a/Desktop/newExcelFile.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();
                        switch(cell.getCellType()) 
                        {
                            case Cell.CELL_TYPE_BOOLEAN:
                                System.out.println("boolean===>>>"+cell.getBooleanCellValue() + "\t");
// write hibernate lines here to store it in your domain
                                break;
                            case Cell.CELL_TYPE_NUMERIC:
                                System.out.println("numeric===>>>"+cell.getNumericCellValue() + "\t");
// write hibernate lines here to store it in your domain
                                break;
                            case Cell.CELL_TYPE_STRING:
                                System.out.println("String===>>>"+cell.getStringCellValue() + "\t");
// write hibernate lines here to store it in your domain
                                break;
                        }
                    }
                    System.out.println("");
                }
                file.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

之后,您可以使用hibernate模式并存储在您的域类中