Java使用POI创建带样式和公式的Excel文件

这篇文章将演示如何使用POI 创建带样式和公式的Excel文件。

代码

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;
import java.io.IOException;

public class ExcelDemo {
  public static void main(String[] args) {
    Workbook workbook = new XSSFWorkbook();
    Sheet sheet = workbook.createSheet("Demo Sheet");

    // 创建标题行并设置样式
    Row headerRow = sheet.createRow(0);
    CellStyle headerStyle = workbook.createCellStyle();
    Font headerFont = workbook.createFont();
    headerFont.setBold(true);
    headerStyle.setFont(headerFont);
    String[] headers = {"Name", "Age", "Salary", "Total"};

    for (int i = 0; i < headers.length; i++) {
      Cell cell = headerRow.createCell(i);
      cell.setCellValue(headers[i]);
      cell.setCellStyle(headerStyle);
    }

    // 创建数据行
    Object[][] data = {
        {"John Doe", 30, 4000},
        {"Jane Smith", 25, 3500},
        {"Jack Johnson", 35, 4500}
    };

    for (int i = 0; i < data.length; i++) {
      Row row = sheet.createRow(i + 1);
      for (int j = 0; j < data[i].length; j++) {
        row.createCell(j).setCellValue(data[i][j].toString());
      }
      // 添加公式计算总数
      row.createCell(data[i].length).setCellFormula(String.format("C%d*12", i + 2));
    }

    // 自动调整列宽
    for (int i = 0; i < headers.length; i++) {
      sheet.autoSizeColumn(i);
    }

    // 写入Excel文件
    try (FileOutputStream fileOut = new FileOutputStream("poi_demo.xlsx")) {
      workbook.write(fileOut);
    } catch (IOException e) {
      e.printStackTrace();
    }

    // 关闭工作簿
    try {
      workbook.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

这个示例代码展示了如何使用Apache POI创建一个包含标题行、数据行、样式和公式的Excel文件,并将其写入文件系统中。

效果图

其他

另外,对以下内容感兴趣的同学请移步对应教程:

GPT-4o 教程

MidJourney教程

Poe教程

Fantia教程

  • 6
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值