首页 文章

如何使用Apache POI制作verticaltext cellstyle?

提问于
浏览
1

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

enter image description here

我用这个垂直文本制作了一个excel文件,并导出为xml文件 . 然后我发现该样式有一个名为'VerticalText'的属性:

enter image description here

根据经验,我选择了Apache POI . 但我找不到任何方法来生成POI的单元格样式 . 我只能找到无法满足要求的旋转方法 .

所以我读了更多的POI代码,发现cellstyles是从一些xsb文件构建的,它也不包含垂直文本 .

任何帮助非常感谢 .

1 回答

  • 1

    您图片中的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创建一个具有所需格式的简单 *.xlsx 文件 . 然后解压缩 *.xlsx 文件并查看 xl/styles.xml .

相关问题