1、创建工作薄,sheet页Workbook workBook = new XSSFWorkbook();Sheet sheet = workBook.createSheet("test");
2、设置单个单元格内容Row row = sheet.createRow(0);row.createCell(0).setCellValue("C");
3、限制此单元格只支持特定内容,如输入其它内容,直接提示错误信息。St筠续师诈ring []values = {"A",&qu泠贾高框ot;B","C","D"};XSSFDataValidationConstraint constraint = new XSSFDataValidationConstraint(values);CellRangeAddressList regions = new CellRangeAddressList(0,0,0,0);DataValidationHelper help = new XSSFDataValidationHelper((XSSFSheet)sheet);DataValidation validation = help.createValidation(constraint, regions);validation.createErrorBox("输入值有误", "请从下拉框中选择");validation.setShowErrorBox(true);sheet.addValidationData(validation);
4、对单元格只能输入数字类型进行限制。row.createCell(1).setCellValue(3);row.createCell(1).setCellType(Cell.CELL_TYPE_NUMERIC)DataValidationConstraint constrain = new XSSFDataValidationConstraint(DataValidationConstraint.ValidationType.INTEGER,DataValidationConstraint.OperatorType.BETWEEN,"1","10");CellRangeAddressList region = new CellRangeAddressList(0,0,1,1);DataValidation vali = help.createValidation(constrain, region);vali.createErrorBox("输入值类型或大小有误", "数值型,请输入1~10之间的数值");validation.setShowErrorBox(true);sheet.addValidationData(vali);
5、把文件保存到特定文件路径下。try {workBook.write(new FileOutputStream("F:/zjc.xlsx"));} catch (FileNotFoundException e) {e.printStackTrace(); } catch (IOException e) {e.printStackTrace();}