java poi 设置背景色,Java Apache Poi,如何同时设置背景颜色和边框

一开始,我想说我是开发人员领域的新手。

我试图生成一个Excel工作表,其中包含带边框的Mutiplication表并设置背景颜色,但仅用于第一列和第一行。

这是一个正确的例子:正确的例子

我写了类似的东西,但是结果文件彩色单元格没有边框:(。

请向我解释如何同时设置背景颜色和边框。

import org.apache.poi.ss.usermodel.Workbook;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import org.apache.poi.ss.usermodel.Sheet;

import org.apache.poi.ss.usermodel.Row;

import org.apache.poi.ss.usermodel.Cell;

import org.apache.poi.ss.usermodel.CellStyle;

import org.apache.poi.ss.usermodel.IndexedColors;

import java.awt.image.IndexColorModel;

import java.io.FileOutputStream;

import java.io.IOException;

import java.util.Scanner;

public class Excel {

public static void main(String[] args) throws IOException {

Scanner in = new Scanner(System.in);

System.out.println("enter number of rows: ");

int x = in.nextInt();

System.out.println("enter number of columns: ");

int y = in.nextInt();

System.out.println("enter name of file: ");

String fileName = in.next() + ".xls";

System.out.println("Multiplication table will be created in file: " + fileName);

createExcelMultiplicationTable(fileName, x, y);

System.out.println("Process successful executed");

}

private static void createExcelMultiplicationTable(String fileName, int x, int y) throws IOException {

Workbook workbook = new HSSFWorkbook();

Sheet sheet = workbook.createSheet("multiplicationTable");

CellStyle backgroundStyle = workbook.createCellStyle();

backgroundStyle.setFillBackgroundColor(IndexedColors.GREY_50_PERCENT.getIndex());

backgroundStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);

CellStyle borderStyle = workbook.createCellStyle();

borderStyle.setBorderBottom(CellStyle.BORDER_THIN);

borderStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());

borderStyle.setBorderLeft(CellStyle.BORDER_THIN);

borderStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());

borderStyle.setBorderRight(CellStyle.BORDER_THIN);

borderStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());

borderStyle.setBorderTop(CellStyle.BORDER_THIN);

borderStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());

for (int i = 1; i <= x; i++) {

Row row = sheet.createRow(i - 1);

for (int j = 1; j <= y; j++) {

Cell cell = row.createCell(j - 1);

cell.setCellValue(i * j);

cell.setCellStyle(borderStyle);

if (cell.getRowIndex() == 0 || cell.getColumnIndex() == 0) {

cell.setCellStyle(backgroundStyle);

}

}

}

FileOutputStream out = new FileOutputStream(fileName);

workbook.write(out);

out.close();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值