POI 并将单元格设置为 VerticalAlignment.MIDDLE

POI and setting cells to VerticalAlignment.MIDDLE

嘿,我正在尝试让我的单元格垂直线,而不是仅仅使用 POI 与左侧对齐。

这是我的 java 代码:

static CellStyle headerCellStyle    = workbook.createCellStyle();

headerCellStyle = workbook.createCellStyle();
Row headerRow   = null;        
sheet           = workbook.createSheet("String " + sheetname);

headerCellStyle.setWrapText(true);
headerCellStyle.setAlignment(HorizontalAlignment.LEFT);
headerCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
headerCellStyle.setVerticalAlignment(VerticalAlignment.MIDDLE);

// Create a Row
headerRow   = sheet.createRow(0);

然而,headerCellStyle.setVerticalAlignment(VerticalAlignment.MIDDLE); 行有一个错误:

The method setVerticalAlignment(org.apache.poi.ss.usermodel.VerticalAlignment) in the type CellStyle is not applicable for the arguments (org.apache.poi.sl.usermodel.VerticalAlignment)

如果我已经将它定义为 static CellStyle headerCellStyle = workbook.createCellStyle();?

,我该如何让它工作

换SS好像没有"middle"选项?

这是 excel 这两种类型的区别:

默认方式:

中道(我想要的方式):

中路:

您的第二张图片(您想要的方式)显示 CellStyle.setVerticalAlignment(VerticalAlignment.CENTER). Your third image shows CellStyle.setAlignment(HorizontalAlignment.CENTER)

setVerticalAlignment(VerticalAlignment.CENTER)setAlignment(HorizontalAlignment.CENTER)有区别。第一个设置 vertical 对齐到中心(又名中间)。第二个设置水平居中对齐。

完整示例:

import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

class CreateExcelVerticalAlignment {

 public static void main(String[] args) throws Exception {

//  try (Workbook workbook = new XSSFWorkbook(); 
//       FileOutputStream fileout = new FileOutputStream("Excel.xlsx") ) {

  try (Workbook workbook = new HSSFWorkbook(); 
       FileOutputStream fileout = new FileOutputStream("Excel.xls") ) {

   CellStyle headerCellStyle = workbook.createCellStyle();
   headerCellStyle = workbook.createCellStyle();
   headerCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

   Sheet sheet = workbook.createSheet();
   sheet.setColumnWidth(0, 20*256);
   Row row = sheet.createRow(0);
   row.setHeightInPoints(40);
   Cell cell = row.createCell(0);
   cell.setCellStyle(headerCellStyle);
   cell.setCellValue("1082192560 1868");

   workbook.write(fileout);
  }

 }
}

结果: