1.写入
package test.testcase; import java.io.*; import java.util.Date; import org.apache.poi.hssf.usermodel.*; /** * @Author: zhanglh * @Date: 2019/2/13 16:15 * @Description: */ public class CreateWorkbook { public static void main(String args[]){ HSSFWorkbook hssfworkbook=new HSSFWorkbook(); File file=new File("test.xls"); if(file.exists()){System.out.println("existing");} else { try { file.createNewFile(); } catch(IOException e){ e.printStackTrace(); } } try { HSSFSheet sheet=hssfworkbook.createSheet("time"); HSSFRow row=sheet.createRow(0); HSSFCell cell=row.createCell(0); cell.setCellValue(new Date()); HSSFCell cell1=row.createCell(1); cell1.setCellValue("verify"); FileOutputStream out=new FileOutputStream(file); hssfworkbook.write(out); out.close(); } catch(IOException e1){ e1.printStackTrace(); } System.out.println("create xlsx successfully"); System.out.println("create sheet successfully"); } }
2.读出
package test.testcase; import java.io.*; import org.apache.poi.hssf.usermodel.*; /** * @Author: zhanglh * @Date: 2019/2/13 17:53 * @Description: */ public class OpenWorkbook { public static void main(String args[]) { File file = new File("test.xls"); try { FileInputStream input = new FileInputStream(file); HSSFWorkbook workbook = new HSSFWorkbook(input); HSSFSheet sheet = workbook.getSheetAt(0); HSSFRow row = sheet.getRow(0); HSSFCell cell = row.getCell(0); /*switch (cell.getCellType()) { case Cell.CELL_TYPE_NUMERIC:*/ System.out.println("cell value:" + cell.getNumericCellValue()); //System.out.println("cell value:" + cell.getStringCellValue()); } catch (IOException e) { e.printStackTrace(); } if (file.exists()) { System.out.println("open"); } else { System.out.println("failure"); } System.out.println("read successfully"); } }
output: