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();
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM