Java教程

java 操作excel

本文主要是介绍java 操作excel,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
需要引入的包 
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
1.创建指定列
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.createSheet();
            HSSFRow row = sheet.createRow(0);
            String[] header = {"序号","(必填*)参数1","参数2","(必填*)参数3","(必填*)参数4","(必填*)参数4"};
            for (int i = 0; i < header.length; i++) {
                HSSFCell cell = row.createCell(i);
                cell.setCellValue(header[i]);
                //自适应列宽
                sheet.setColumnWidth(i,header[i].getBytes().length * 256);

                //设置列样式,水平、垂直居中,不允许修改,超过长度则自动换行
                HSSFCellStyle cellStyle = workbook.createCellStyle();
                cellStyle.setAlignment(HorizontalAlignment.CENTER);
                cellStyle.setLocked(true);
                cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
                cellStyle.setWrapText(true);
                //设置富文本属性,这里只让【必填*】变为红色
                if(header[i].indexOf("*") != -1){
                    HSSFFont font = workbook.createFont();
                    font.setColor(HSSFFont.COLOR_RED);
                    cell.getRichStringCellValue().applyFont(1,4,font);
                }
                cell.setCellStyle(cellStyle);
            }
2.列表新增下拉列表
          HSSFSheet sheet = workbook.getSheetAt(0);
      List<String> downList = Arrays.asList("下拉1","下拉2")
      downList.add(0, "下拉列表头新增");
      String[] strings = new String[downList.size()];
      downList.toArray(strings);

      DVConstraint constraint = DVConstraint.createExplicitListConstraint(strings);
      // 参数 开始行数,结束行数,开始列,结束列。表示需要哪些列、哪些行默认是下拉列表选项
      CellRangeAddressList regions = new CellRangeAddressList(1, 1, 2, 2);
      HSSFDataValidation dataValidation = new HSSFDataValidation(regions, constraint);
      sheet.addValidationData(dataValidation);

  

这篇关于java 操作excel的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!