Java POI 常用操作
POI 常用操作
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* @author longrong.lang
* @version 1.0
* @description
* @date 2020/9/15 9:32
*/
public class MergeCellDemo {
public static void main(String[] args) throws IOException {
//新建工作簿
XSSFWorkbook xssfWorkbook = new XSSFWorkbook();
//新建工作表
XSSFSheet sheet = xssfWorkbook.createSheet("工作表1");
//指定合并开始行、合并结束行 合并开始列、合并结束列
CellRangeAddress rangeAddress = new CellRangeAddress(0, 0, 0, 1);
//添加要合并地址到表格
sheet.addMergedRegion(rangeAddress);
//创建行,指定起始行号,从0开始
XSSFRow row = sheet.createRow(0);
//创建单元格,指定起始列号,从0开始
XSSFCell cell = row.createCell(0);
//设置单元格内容
cell.setCellValue("我是合并后的单元格");
//创建样式对象
CellStyle style = xssfWorkbook.createCellStyle();
//设置样式对齐方式:水平\垂直居中
style.setAlignment(HorizontalAlignment.CENTER);
style.setVerticalAlignment(VerticalAlignment.CENTER);
//设定填充单色
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
//设定背景颜色
style.setFillForegroundColor(IndexedColors.PINK.getIndex());
//为指定单元格设定样式
cell.setCellStyle(style);
FileOutputStream fileOutputStream = new FileOutputStream("d:\\MergeCellDemo.xlsx");
xssfWorkbook.write(fileOutputStream);
fileOutputStream.close();
}
}
linhuaming