Apache POI Excel 单元格对齐

Apache POI 有助于以某种方式对齐单元格及其内容。我们可以设置单元格的高度和宽度并将其顶部或底部对齐。Sheet 类提供了设置高度和宽度的方法。

让我们看一个示例,其中我们正在创建一个单元格并对齐它。

Apache POI Excel 单元格对齐示例

package com.yiidian;

import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class AlignExample {
    public static void main(String[] args) throws FileNotFoundException, IOException {
        Workbook wb = new HSSFWorkbook();
        try  (OutputStream os = new FileOutputStream("yiidian.xls")) {
            Sheet sheet = wb.createSheet("New Sheet");
            Row row = sheet.createRow(0);
            Cell cell = row.createCell(0);
            cell.setCellValue("一点教程网");
            CellStyle cellStyle = wb.createCellStyle();
            row = sheet.createRow(5);   
            cell = row.createCell(0);  
            // Top Left alignment   
            HSSFCellStyle style1 = (HSSFCellStyle) wb.createCellStyle();
            sheet.setColumnWidth(0, 8000);  
            cell.setCellValue("Top Left");  
            cell.setCellStyle(style1);  
            row = sheet.createRow(6);   
            cell = row.createCell(1);  
            row.setHeight((short) 800);  
            wb.write(os);  
        }catch(Exception e) {  
            System.out.println(e.getMessage());  
        }  
    }  
  
}  

输出结果为:

热门文章

优秀文章