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);

  

上一篇:FLV格式详解


下一篇:python数据分析——pandas的拼接操作