您的当前位置:首页正文

poi创建下拉框

2024-11-25 来源:个人技术集锦

poi创建下拉框


package com.cloud.poi.utils;
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;
import org.apache.poi.ss.SpreadsheetVersion;
/**
 * poi创建下拉框
 * @author Henry
 */
public class PoiCheckBox97
{
	public static void main(String[] args)
	{
		String[] list = { "JAVA", "C", "易语言", "GO" };
		new PoiCheckBox97().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("请选择");// 这是实验
		// 生成下拉列表
		// 对(row0,rowMax,col0,colMax)所有单元格有效
		int maxRowNum = SpreadsheetVersion.EXCEL97.getLastRowIndex();//maxRowNum=65535
		System.out.println("maxRowNum:"+maxRowNum);
		int maxColNum = SpreadsheetVersion.EXCEL97.getLastColumnIndex();
		System.out.println("maxColNum:"+maxColNum);//maxColNum=255
		CellRangeAddressList regions = new CellRangeAddressList(0, maxRowNum, 0, maxColNum);
		// 生成下拉框内容
		DVConstraint constraint = DVConstraint
				.createExplicitListConstraint(list);
		// 绑定下拉框和作用区域
		HSSFDataValidation data_validation = new HSSFDataValidation(regions,
				constraint);
		// 对sheet页生效
		sheet.addValidationData(data_validation);
		// 写入文件
		FileOutputStream fileOut;
		try {
			fileOut = new FileOutputStream("d:/workbook.xls");
			wb.write(fileOut);
			fileOut.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 结束
		System.out.println("Over");
	}
}


显示全文