poi excel设置行间距
时间: 2023-08-23 15:04:42 浏览: 570
在使用POI操作Excel时,可以通过设置CellStyle的属性来设置行间距。
具体操作步骤如下:
1. 获取Workbook对象。
2. 创建CellStyle对象。
3. 设置CellStyle的行高和字体属性,其中行高的单位是1/20个点。
```java
// 创建CellStyle对象
CellStyle cellStyle = workbook.createCellStyle();
// 设置行高
cellStyle.setRowHeight((short) (20 * 20));
// 创建字体对象
Font font = workbook.createFont();
// 设置字体大小
font.setFontHeightInPoints((short) 12);
// 设置字体
font.setFontName("宋体");
// 设置字体样式
font.setBoldweight(Font.BOLDWEIGHT_NORMAL);
// 设置字体颜色
font.setColor(IndexedColors.BLACK.getIndex());
// 设置行间距
font.setLineSpacing((short) 300);
// 将字体应用到CellStyle
cellStyle.setFont(font);
```
4. 将CellStyle应用到需要设置行间距的行。
```java
// 获取Sheet对象
Sheet sheet = workbook.getSheetAt(0);
// 获取第一行
Row row = sheet.getRow(0);
// 将CellStyle应用到第一行
row.setRowStyle(cellStyle);
```
完整示例代码如下:
```java
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
public class PoiExcelSetRowSpacingDemo {
public static void main(String[] args) throws IOException {
// 创建Workbook对象
Workbook workbook = new HSSFWorkbook();
// 创建Sheet对象
Sheet sheet = workbook.createSheet("Sheet1");
// 创建Row对象
Row row = sheet.createRow(0);
// 创建Cell对象
row.createCell(0).setCellValue("Hello World!");
// 创建CellStyle对象
CellStyle cellStyle = workbook.createCellStyle();
// 设置行高
cellStyle.setRowHeight((short) (20 * 20));
// 创建字体对象
Font font = workbook.createFont();
// 设置字体大小
font.setFontHeightInPoints((short) 12);
// 设置字体
font.setFontName("宋体");
// 设置字体样式
font.setBoldweight(Font.BOLDWEIGHT_NORMAL);
// 设置字体颜色
font.setColor(IndexedColors.BLACK.getIndex());
// 设置行间距
font.setLineSpacing((short) 300);
// 将字体应用到CellStyle
cellStyle.setFont(font);
// 将CellStyle应用到第一行
row.setRowStyle(cellStyle);
// 保存Excel文件
FileOutputStream fos = new FileOutputStream("test.xls");
workbook.write(fos);
fos.close();
}
}
```
阅读全文
相关推荐
















