web-dev-qa-db-fra.com

Java Apache Poi, comment définir la couleur d'arrière-plan et les bordures en même temps

au début, je veux dire que je suis totalement nouveau dans le monde des développeurs.

J'ai essayé de générer une feuille Excel qui contient une table de multiplication avec des bordures et une couleur d'arrière-plan définie, mais uniquement pour la 1ère colonne et la première ligne.

Voici un exemple correct: exemple correct

J'ai écrit quelque chose comme ça, mais dans le résultat, les cellules colorées n'ont pas de bordures :(.

Veuillez m'expliquer comment définir la couleur d'arrière-plan et les bordures en même temps.

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
Robert Lewandowski

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

 backgroundStyle.setFillForegroundColor(IndexedColors.YELLOW.getIndex());

Et vous pouvez définir la bordure comme ci-dessous:

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

Cela vous donnera une couleur jaune et une bordure au besoin

10
Karthik

Votre vrai problème est que vous avez deux styles, l'un nommé backgroundStyle et l'autre nommé borderStyle. Vous appliquez ensuite les deux styles à la même cellule, mais une cellule ne peut avoir qu'un seul style. Par conséquent, au lieu d'ajouter le deuxième style, vous remplacez le premier style par le deuxième style.

Au lieu de:

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

Créez simplement un style unique comme celui-ci:

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

Ensuite, appliquez cela à votre cellule:

    Sheet sheet = workbook.createSheet();
    Row row = sheet.createRow(1);
    Cell cell = row.createCell(1);
    cell.setCellStyle(backgroundStyle);

REMARQUE: Comme mentionné dans d'autres réponses ici, la couleur d'arrière-plan est ignorée pour FillPattern = SOLID_FOREGROUND, vous devez définir la couleur de premier plan pour ce motif. Cela peut être déroutant car vous essayez de définir l'arrière-plan de la cellule sur une couleur unie. Mais cell background n'est pas la même chose que background color. Cell background est le même que Fill Pattern qui a deux couleurs a Foreground Color et un Background Color ceux-ci sont affichés en fonction du Fill Pattern sélectionné. Le SOLID_FOREGROUND fill utilise uniquement le Foreground Color.

10
jmarkmurphy

Depuis POI 3.x, la couleur de remplissage des cellules est définie comme suit:

CellStyle cs = wb.createCellStyle();
cs.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
cs.setFillPattern(FillPatternType.SOLID_FOREGROUND);
9
Slawomir

J'ai trouvé un moyen de résoudre ce problème, mais je suis presque sûr qu'il existe un autre moyen plus court.

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