Search code examples
javatextboxapache-poirichtextbox

Apache POI textbox looks different from excel textbox


POI textbox vs Excel textbox

I want to make a textbox which looks like the one on the right in the image shown above. I tried following the documentation and wrote the following code.

public void TestXSSFPatriarch(String fileName, String richText) {
    Workbook workbook = new XSSFWorkbook();
    Sheet sheet = workbook.createSheet("hssf");
    XSSFDrawing xssfDrawing = (XSSFDrawing) sheet.createDrawingPatriarch();
    XSSFTextBox xssfTextBox = xssfDrawing.createTextbox(
            new XSSFClientAnchor(0, 0, 25, 50, (short) 0, 0, (short) 25, 50));
    xssfTextBox.setText(new XSSFRichTextString(richText));

    try (OutputStream fileOut = new FileOutputStream(fileName)) {
        workbook.write(fileOut);
        System.out.println("Success");
    } catch (IOException e) {
        e.printStackTrace();
    }
}

The above code outputs the textbox which is shown on the left in the above image. Any help on this would be highly appreciated.


Solution

  • After trying out a different methods provided by the XSSFTextBox. I found an option named setFillColor

    public void TestXSSFPatriarch(String fileName, String richText) {
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("hssf");
        XSSFDrawing xssfDrawing = (XSSFDrawing) sheet.createDrawingPatriarch();
        XSSFTextBox xssfTextBox = xssfDrawing.createTextbox(
                new XSSFClientAnchor(0, 0, 25, 50, (short) 0, 0, (short) 25, 50));
        xssfTextBox.setText(new XSSFRichTextString(richText));
    
        xssfTextBox.setFillColor(255, 255, 255); // Adding the following line solved the problem
        
        try (OutputStream fileOut = new FileOutputStream(fileName)) {
            workbook.write(fileOut);
            System.out.println("Success");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }