本文共 2631 字,大约阅读时间需要 8 分钟。
poi读取Excel中的日期类型和int类型
代码如下:/* 使用poi 读取excel文件 中的数据 */ @Test public void read() throws IOException { //1.使用 流的方式 读取文件 FileInputStream fileInputStream = new FileInputStream(new File("C:\\Users\\xiaoman\\Desktop\\poi.xlsx")); //2.使用 xssf去创建 我们的workbook XSSFWorkbook excel = new XSSFWorkbook(fileInputStream); //3.根据索引 获取 sheet XSSFSheet sheet = excel.getSheetAt(0); //4.遍历row for (Row row : sheet) { System.out.println(row); for (Cell cell : row) { //判断是否是日期类型 if ("yyyy/mm;@".equals(cell.getCellStyle().getDataFormatString()) || "m/d/yy".equals(cell.getCellStyle().getDataFormatString()) || "yy/m/d".equals(cell.getCellStyle().getDataFormatString()) || "mm/dd/yy".equals(cell.getCellStyle().getDataFormatString()) || "dd-mmm-yy".equals(cell.getCellStyle().getDataFormatString()) || "yyyy/m/d".equals(cell.getCellStyle().getDataFormatString())) { System.out.println(new SimpleDateFormat("yyyy/MM/dd").format(cell.getDateCellValue())); } else if (cell.getCellType() == cell.CELL_TYPE_NUMERIC) { //判断是否是int类型 System.out.println((int) cell.getNumericCellValue()); } else { System.out.println(cell.getStringCellValue()); } } } //5.关闭excel excel.close(); }
poi在Excel中写入数据
代码如下:/* 使用poi写入到 磁盘 */ @Test public void write() throws IOException { //1.使用流的方式 FileOutputStream fileOutputStream = new FileOutputStream(new File("C:\\Users\\xiaoman\\Desktop\\poi2.xlsx")); //2.创建excel对象 XSSFWorkbook excel = new XSSFWorkbook(); //3.创建sheet XSSFSheet sheet = excel.createSheet("新的sheet"); XSSFRow title = sheet.createRow(0); //4.创建 cell //第一行 title.createCell(0).setCellValue("姓名"); title.createCell(1).setCellValue("年龄"); title.createCell(2).setCellValue("性别"); title.createCell(3).setCellValue("手机号"); title.createCell(4).setCellValue("地址"); //第二行 XSSFRow row = sheet.createRow(1); row.createCell(0).setCellValue("张三"); row.createCell(1).setCellValue("18"); row.createCell(2).setCellValue("男"); row.createCell(3).setCellValue("1355464232"); row.createCell(4).setCellValue("河南郑州"); //5.写到excel中 excel.write(fileOutputStream); //6.关闭excel fileOutputStream.flush();//刷新此输出流并强制写出任何缓冲输出字节 excel.close(); }
转载地址:http://xlbki.baihongyu.com/