位置:首页 » 文章/教程分享 » Apache POI 设置宽度和行高

1. Excel列宽单位概述

POI中Sheet列宽是通过字符个数来确定的,列宽单位为一个字符宽度的1/256
每列可以显示的最大字符数为255
// 设置默认列宽,width为字符个数
sheet.setDefaultColumnWidth(int width)

// 设置第columnIndex+1列的列宽,单位为字符宽度的1/256
sheet.setColumnWidth(int columnIndex, int width)
// 设置第5列的列宽为20个字符宽度
sheet.setColumnWidth(4, 20*256)

2. 列实际显示字符个数

setColumnWidth(int columnIndex, int width)设置的宽度包括4像素的边距填充(每侧两个),加上网格线的1像素填充。

如果字符宽度为w像素, w单位为一个字符宽度的1/256,设置列宽字符个数为count,则实际可见字符数X:
    X * (w * 256) + 5 = count * (w * 256) 
转换公式:
    X = count - 5/w
可见实际可见字符数比设置字符数略小

字符宽度大小为多少?

    使用默认字体Font(Workbook中定义的第一个字体)渲染数字0,1,2,3,4,5,6,7,8,9,其中宽度最大的作为字符宽度
    如果使用非常特殊的字体,默认数字为0,默认渲染字体为Arial(HSSF)和Calibri(XSSF)

以Calibri字体为例,11点字体大小的最大数字宽度为7像素(96 dpi),如果将列宽设置为8个字符宽。则实际可见字符数(Excel中显示值):
   X = count - 5/w = 8 - 5/7 = 7.29
则该列实际只能显示7.29个字符,第8个字符被遮盖部分

3. 实例

package hssf.sheet;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.WorkbookUtil;

public class ExportSetColWidth {


    public static void main(String[] args) throws IOException {
        File file = new File("C:\\Users\\Administrator\\Desktop\\test.xls");
        if (file.exists()) {
            file.delete();
        }
        BufferedOutputStream out = null;
        try {
            out = new BufferedOutputStream(new FileOutputStream("C:\\Users\\Administrator\\Desktop\\test.xls"));
            exportExcel(out);
        } finally {
            out.close();
        }
    }

    private static void exportExcel(BufferedOutputStream out) throws IOException {
        Workbook workbook = new HSSFWorkbook();
        // 格式化Sheet名,使其合法
        String safeSheetName = WorkbookUtil.createSafeSheetName("设置列宽");
        Sheet sheet = workbook.createSheet(safeSheetName);

        sheet.setDefaultColumnWidth(4);
        sheet.setColumnWidth(4, 20*256);
        sheet.setColumnWidth(5, 25*256);
        sheet.setColumnWidth(6, 30*256);
        sheet.setColumnWidth(7, 35*256);

        Row row0 = sheet.createRow(0);
        row0.createCell(4).setCellValue("列宽: 20个字符宽");
        row0.createCell(5).setCellValue("列宽: 25个字符宽");
        row0.createCell(6).setCellValue("列宽: 30个字符宽");
        row0.createCell(7).setCellValue("列宽: 35字符宽");

        workbook.write(out);
    }

}