How to make verticaltext cellstyle with Apache POI

2019-06-03 16:27发布

问题:

Recently, I met a question: I need to export an excel(xlsx) with java, which must contain this kind of cell style:

I made a excel file with this vertical text, and exported as a xml file. Then I found that the style has an attribute named 'VerticalText':

By experience, I chose Apache POI. But I couldn't find any way to generate the cell style with POI. I could only find rotate method, which could't meet the requirement.

So I read more code of POI, and found that the cellstyles are build from some xsb file, which do not contain vertical text either.

Any help much appreciated.

回答1:

The XML in your picture is Excel 2003 SpreadsheetML. But an *.xlsx file is a ZIP archive containing Office Open XML files. In that ZIP archive the styles.xml contains:

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

There <alignment textRotation="255"/> is for vertical text.

This can be set using apache poi like so:

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

Since the Office Open XML formats (like *.xlsx) are ZIP archives containing XML files it is pretty easy to determine the necessary XML attributes. Simply create a simple *.xlsx file having the needed formatting using the Excel GUI. Then unzip the *.xlsx file and have a look at xl/styles.xml.