首先展示一下表格:
获取总行数和总列数:
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!,后面雷同!