1. 程式人生 > 其它 >Java POI 常用操作

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

參考:https://blog.51cto.com/u_15009374/3147413