简体   繁体   English

如何使用Apache POI制作Verticaltext CellStyle?

[英]How to make verticaltext cellstyle with Apache POI?

Recently, I met a question: I need to export an excel(xlsx) with java, which must contain this kind of cell style: 最近,我遇到一个问题:我需要使用Java导出excel(xlsx),其中必须包含这种单元格样式:

在此处输入图片说明

I made a excel file with this vertical text, and exported as a xml file. 我用此垂直文本制作了一个excel文件,并导出为xml文件。 Then I found that the style has an attribute named 'VerticalText': 然后,我发现样式具有名为“ VerticalText”的属性:

在此处输入图片说明

By experience, I chose Apache POI. 根据经验,我选择了Apache POI。 But I couldn't find any way to generate the cell style with POI. 但是我找不到用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. 因此,我阅读了更多关于POI的代码,并发现单元样式是从xsb文件构建的,该文件也不包含垂直文本。

Any help much appreciated. 任何帮助,不胜感激。

The XML in your picture is Excel 2003 SpreadsheetML. 图片中的XML是Excel 2003 SpreadsheetML。 But an *.xlsx file is a ZIP archive containing Office Open XML files. 但是*.xlsx文件是包含Office Open XML文件的ZIP存档。 In that ZIP archive the styles.xml contains: 在该ZIP存档中, styles.xml包含:

...
<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. <alignment textRotation="255"/>用于垂直文本。

This can be set using apache poi like so: 可以使用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();
 }
}

Since the Office Open XML formats (like *.xlsx ) are ZIP archives containing XML files it is pretty easy to determine the necessary XML attributes. 由于Office Open XML格式(例如*.xlsx )是包含XML文件的ZIP存档,因此确定必要的XML属性非常容易。 Simply create a simple *.xlsx file having the needed formatting using the Excel GUI. 只需使用Excel GUI创建具有所需格式的简单*.xlsx文件。 Then unzip the *.xlsx file and have a look at xl/styles.xml . 然后解压缩*.xlsx文件并查看xl/styles.xml

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM