Java Apache Poi, как установить цвет фона и границы одновременно
в начале я хочу сказать, что я совершенно новый в мире разработчиков.
Я попытался создать лист excel, содержащий таблицу Mutiplication с границами и установить цвет фона, но только для 1-го столбца и строки.
вот правильный пример: правильный пример
Я написал что-то подобное, но в результирующем файле цветные ячейки не имеют границ :(.
пожалуйста, объясните мне, как установить цвет фона и границы на в то же время.
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();
}
}
4 ответов
изменить backgroundStyle.setFillBackgroundColor(IndexedColors.GREY_50_PERCENT.getIndex());
to
backgroundStyle.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
и вы можете установить границы, как показано ниже :
backgroundStyle.setBorderBottom(CellStyle.BORDER_THIN);
backgroundStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());
backgroundStyle.setBorderLeft(CellStyle.BORDER_THIN);
backgroundStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());
backgroundStyle.setBorderRight(CellStyle.BORDER_THIN);
backgroundStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());
backgroundStyle.setBorderTop(CellStyle.BORDER_THIN);
backgroundStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());
Это даст вам желтый цвет и границу по мере необходимости
ваша реальная проблема заключается в том, что у вас есть два стиля, один с именем backgroundStyle, а другой с именем borderStyle. Затем вы применяете оба стиля к одной ячейке, но ячейка может иметь только один стиль, поэтому вместо добавления второго стиля вы перезаписываете первый стиль вторым стилем.
вместо:
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());
просто создайте один стиль, как это:
CellStyle backgroundStyle = workbook.createCellStyle();
backgroundStyle.setFillBackgroundColor(IndexedColors.GREY_50_PERCENT.getIndex());
backgroundStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
backgroundStyle.setBorderBottom(CellStyle.BORDER_THIN);
backgroundStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());
backgroundStyle.setBorderLeft(CellStyle.BORDER_THIN);
backgroundStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());
backgroundStyle.setBorderRight(CellStyle.BORDER_THIN);
backgroundStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());
backgroundStyle.setBorderTop(CellStyle.BORDER_THIN);
backgroundStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());
затем примените это к своему ячейка:
Sheet sheet = workbook.createSheet();
Row row = sheet.createRow(1);
Cell cell = row.createCell(1);
cell.setCellStyle(backgroundStyle);
Примечание: как упоминалось в других ответах здесь, цвет фона игнорируется для FillPattern = SOLID_FOREGROUND, вы должны установить цвет переднего плана для этого шаблона. Это может быть запутанным, потому что вы пытаетесь установить фон ячейки в сплошной цвет. Но!--3--> - это не то же самое как background color
. Cell background
это то же самое, что Fill Pattern
, который имеет два цвета Foreground Color
и Background Color
они отображаются на основе конкретных Fill Pattern
выбранные. Этот SOLID_FOREGROUND
fill использует только Foreground Color
.
по состоянию на POI 3.x, цвет заливки ячейки устанавливается следующим образом:
CellStyle cs = wb.createCellStyle(); цезий.setFillForegroundColor (IndexedColors.GREY_25_PERCENT.метода getIndex()); цезий.setFillPattern(FillPatternType.SOLID_FOREGROUND);
Я нашел один способ, как решить эту проблему, но я почти уверен, что есть другой более короткий путь.
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.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");
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);
if (cell.getRowIndex() == 0 || cell.getColumnIndex() == 0) {
CellStyle Style = workbook.createCellStyle();
Style.setFillBackgroundColor(IndexedColors.GREY_50_PERCENT.getIndex());
Style.setFillPattern(CellStyle.BIG_SPOTS);
Style.setBorderBottom(CellStyle.BORDER_THIN);
Style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
Style.setBorderLeft(CellStyle.BORDER_THIN);
Style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
Style.setBorderRight(CellStyle.BORDER_THIN);
Style.setRightBorderColor(IndexedColors.BLACK.getIndex());
Style.setBorderTop(CellStyle.BORDER_THIN);
Style.setTopBorderColor(IndexedColors.BLACK.getIndex());
cell.setCellStyle(Style);
} else {
CellStyle Style = workbook.createCellStyle();
Style.setBorderBottom(CellStyle.BORDER_THIN);
Style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
Style.setBorderLeft(CellStyle.BORDER_THIN);
Style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
Style.setBorderRight(CellStyle.BORDER_THIN);
Style.setRightBorderColor(IndexedColors.BLACK.getIndex());
Style.setBorderTop(CellStyle.BORDER_THIN);
Style.setTopBorderColor(IndexedColors.BLACK.getIndex());
cell.setCellStyle(Style);
}
}
}
FileOutputStream out = new FileOutputStream(fileName);
workbook.write(out);
out.close();
}
}