Java如何設定單元格中的文字的方向?

2019-10-16 22:27:46

在Java程式設計中,如何設定單元格中的文字的方向?

注意:需要存取網址:http://poi.apache.org/download.html , 下載一個Apache POI軟體包。這裡下載最新版本:poi-bin-3.17-20170915.tar.gz解壓並將全部.jar檔案匯入 。

需要匯入全部包,如下圖所示 -

參考範例:

http://poi.apache.org/spreadsheet/quick-guide.html

以下是使用Java設定單元格中的文字的方向的程式。

package com.yiibai;

import java.io.File;
import java.io.FileOutputStream;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class TextDirectionInCell {
    public static void main(String[] args) throws Exception {

        // Creating Workbook
        XSSFWorkbook workbook = new XSSFWorkbook();

        // Creating a Spread Sheet
        XSSFSheet spreadsheet = workbook.createSheet("Text direction");
        XSSFRow row = spreadsheet.createRow(2);
        XSSFCellStyle myStyle = workbook.createCellStyle();
        myStyle.setRotation((short) 0);
        XSSFCell cell = row.createCell(1);

        cell.setCellValue("0D angle");
        cell.setCellStyle(myStyle);

        // 30 degrees
        myStyle = workbook.createCellStyle();
        myStyle.setRotation((short) 30);

        cell = row.createCell(3);
        cell.setCellValue("30D angle");
        cell.setCellStyle(myStyle);

        // 90 degrees
        myStyle = workbook.createCellStyle();
        myStyle.setRotation((short) 90);

        cell = row.createCell(5);
        cell.setCellValue("90D angle");
        cell.setCellStyle(myStyle);

        // 120 degrees
        myStyle = workbook.createCellStyle();
        myStyle.setRotation((short) 120);

        cell = row.createCell(7);
        cell.setCellValue("120D angle");
        cell.setCellStyle(myStyle);

        // 270 degrees
        myStyle = workbook.createCellStyle();
        myStyle.setRotation((short) 270);
        cell = row.createCell(9);
        cell.setCellValue("270D angle");
        cell.setCellStyle(myStyle);

        // 360 degrees
        myStyle = workbook.createCellStyle();
        myStyle.setRotation((short) 360);

        cell = row.createCell(12);
        cell.setCellValue("360D angle");
        cell.setCellStyle(myStyle);
        FileOutputStream out = new FileOutputStream(new File("textdirection.xlsx"));

        workbook.write(out);
        out.close();

        System.out.println("textdirection.xlsx written successfully");
    }
}

執行上面範例程式碼,得到以下結果 -

textdirection.xlsx written successfully

建立的Excel檔案內容,如下所示 -