JAVA-POI

x33g5p2x  于2022-02-11 转载在 Java  
字(1.6k)|赞(0)|评价(0)|浏览(260)

首先展示一下表格:

获取总行数和总列数:

String path = "D:\\C桌面\\CSDN学习计划\\技术训练营\\Excel表格学习\\";
   FileInputStream fileInputStream = new FileInputStream(path + "persion.xlsx");
        Workbook workbook = new XSSFWorkbook(fileInputStream);
        Sheet sheet = workbook.getSheetAt(0);
        //总列数
        Row hssfRow=sheet.getRow(0);
        int columnNum=hssfRow.getPhysicalNumberOfCells();
        //总行数
        int rowNum=sheet.getLastRowNum();

获取第一列:

FileInputStream fileInputStream = new FileInputStream(path + "persion.xlsx");
        Workbook workbook = new XSSFWorkbook(fileInputStream);
        Sheet sheet = workbook.getSheetAt(0);
           int rowNum=sheet.getLastRowNum();
        for (int i = 0; i <rowNum; i++) {
            Row row = sheet.getRow(i);
            Cell cell = row.getCell(0);
            System.out.println(cell.getStringCellValue());

        }

将第一列存入数据库:

/**
     * 存入第一列
     */
    @Test
    public void  cell1() throws IOException, SQLException {
        TestDao test = new TestDao();
        FileInputStream fileInputStream = new FileInputStream(path + "persion.xlsx");
        Workbook workbook = new XSSFWorkbook(fileInputStream);
        Sheet sheet = workbook.getSheetAt(0);
        //总列数
        Row hssfRow = sheet.getRow(0);
        int columnNum = hssfRow.getPhysicalNumberOfCells();
        //总行数
        int rowNum = sheet.getLastRowNum();

        for (int i = 1; i < rowNum; i++) {
            Row row = sheet.getRow(i);
            Cell cell = row.getCell(0);
            String value = cell.getStringCellValue();
            test.cun(value,i);
            System.out.println("存入成功!");

        }
    }

dao层:

/**
     * 将第一列存入数据库
     */
    public  void  cun(String value,Integer id) throws SQLException {
        Connection connection = null;
        PreparedStatement pr = null;
        connection = DBUtil.getConnection();
        String sql = "insert into excel(id,name) values('"+id+"','"+value+"')";
        pr = connection.prepareStatement(sql);
        int count =pr.executeUpdate();
    }

这里记住存入第二列的时候就不可以用insert了就需要用update!,后面雷同!

相关文章

最新文章

更多