如何使用Apache POI创buildverticaltext cellstyle?

最近,我遇到了一个问题:我需要用java导出一个excel(xlsx),它必须包含这种单元格样式:

在这里输入图像说明

我用这个垂直文本做了一个excel文件,然后导出为一个xml文件。 然后我发现这个样式有一个名为“VerticalText”的属性:

在这里输入图像说明

根据经验,我select了Apache POI。 但是我找不到用POI生成单元格样式的方法。 我只能find旋转的方法,不能满足要求。

所以我读了更多的POI代码,发现这个cellstyles是由一些xsb文件构build的,它们也不包含垂直文本。

任何帮助非常感谢。

图片中的XML是Excel 2003 SpreadsheetML。 但一个*.xlsx文件是一个包含Office Open XML文件的ZIP压缩文件。 在该ZIP压缩文件中, styles.xml包含:

 ... <cellXfs count="2"> ... <xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"> <alignment textRotation="255"/> </xf> </cellXfs> ... 

<alignment textRotation="255"/>是垂直文本。

这可以使用apache poi来设置,如下所示:

 import java.io.FileOutputStream; import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class CreateXSSFVerticalText { public static void main(String[] args) throws Exception { Workbook workbook = new XSSFWorkbook(); CellStyle cellStyle = workbook.createCellStyle(); cellStyle.setRotation((short)255); Sheet sheet = workbook.createSheet(); Row row = sheet.createRow(0); Cell cell = row.createCell(0); cell.setCellValue("test"); cell.setCellStyle(cellStyle); FileOutputStream fileOut = new FileOutputStream("CreateXSSFVerticalText.xlsx"); workbook.write(fileOut); fileOut.close(); workbook.close(); } } 

由于Office Open XML格式(如*.xlsx )是包含XML文件的ZIP存档,因此确定必要的XML属性非常容易。 只需使用Excel GUI创build一个具有所需格式的简单*.xlsx文件。 然后解压缩*.xlsx文件并查看xl/styles.xml