嘿,我正在尝试将自己的单元格设置为垂直线,而不是仅使用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);错误为:


  CellStyle类型的setVerticalAlignment(org.apache.poi.ss.usermodel.VerticalAlignment)方法不适用于参数(org.apache.poi.sl.usermodel.VerticalAlignment)


如果已经将其定义为静态CellStyle headerCellStyle = workbook.createCellStyle();,该如何使其正常工作?

更改为SS似乎没有“中间”选项?

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

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

默认方式:

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

中间方式(我想要的方式):

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

中心方式:

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

最佳答案

第二张图像(您想要的方式)显示CellStyle.setVerticalAlignment(VerticalAlignment.CENTER)。您的第三个图像显示CellStyle.setAlignment(HorizontalAlignment.CENTER)

setVerticalAlignment(VerticalAlignment.CENTER)setAlignment(HorizontalAlignment.CENTER)之间有区别。第一个将垂直对齐方式设置为中心(也称为中间)。第二个将水平对齐方式设置为居中。

完整的例子:

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

 }
}


结果:

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

08-18 13:25