想要使用POI操作以xsl结尾的Excel,首先要下载poi相关的jar包,用到的jar有:
poi-3.9.jar
poi-ooxml-3.9.jar
poi-ooxml-schemas-3.9.jar
一、生成第一种下拉框样式:
上代码:
package com.imtdata.dropdownbox; import java.io.FileOutputStream; import org.apache.poi.hssf.usermodel.DVConstraint; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFDataValidation; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.util.CellRangeAddressList; public class POI { public static void main(String[] args) { String[] list = { "东软", "华信", "SAP", "海辉" }; new POI().createListBox(list); return; } public void createListBox(String[] list) { // 文件初始化 HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet sheet = wb.createSheet("new sheet"); // 在第一行第一个单元格,插入下拉框 HSSFRow row = sheet.createRow(0); HSSFCell cell = row.createCell(0); // 普通写入操作 cell.setCellValue("请选择");// 这是实验 // 生成下拉列表 // 只对(0,0)单元格有效 CellRangeAddressList regions = new CellRangeAddressList(0, 0, 0, 0); // 生成下拉框内容 DVConstraint constraint = DVConstraint.createExplicitListConstraint(list); // 绑定下拉框和作用区域 HSSFDataValidation data_validation = new HSSFDataValidation(regions, constraint); // 对sheet页生效 sheet.addValidationData(data_validation); // 写入文件 FileOutputStream fileOut; try { fileOut = new FileOutputStream("workbook.xls"); wb.write(fileOut); fileOut.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } // 结束 System.out.println("Over"); } }
二、生成第二种下拉框样式:
上代码:
其中最重要的就是两行代码
public static void writeExcel(OutputStream outputStream,String[] fieldName) { try { // 创建一个webbook,对应一个Excel文件 HSSFWorkbook wb = new HSSFWorkbook(); // 在webbook中添加一个sheet,对应Excel文件中的sheet HSSFSheet s = wb.createSheet(); // createTag(fieldName,s);//写表格的头部 //创建单元格,并设置值表头 设置表头居中 HSSFCellStyle style = wb.createCellStyle(); style.setAlignment(HSSFCellStyle.ALIGN_CENTER); CellRangeAddress c = (CellRangeAddress) CellRangeAddress.valueOf("B1"); s.setAutoFilter(c); wb.write(outputStream); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }