javaandroidexcelalignmentjxl

Jxl cell alignment


i want to know how can i set an alignment for cell in jxl library , it's default alignment is bottom and when i set alignment for WritableCellFormat it throws me this Exception :

jxl.write.biff.JxlWriteException: Attempt to modify a referenced format

i set alignment this way :

WritableFont tahomaboldpt = new WritableFont(WritableFont.TAHOMA, 10,WritableFont.BOLD);
tahomaBold = new WritableCellFormat(tahomaboldpt);
tahomaBold.setAlignment(Alignment.CENTRE);

this throws me Exception in third line.Thanks in Advance


Solution

  • You need to create a WritableCellFormat object and pass this as an argument, when you want to create or add a cell in spreadsheet with the specified format.

    Step 1: you can read the format from another cell (just like the below code or create a new one on your own) and then create a WritableCellFormat Object[newFormat object in below code]

    Step 2: Add all the formatting you want example background , border, alignment etc as shown in the below code.

    WritableCellFormat newFormat = null;
    WritableSheet sheet = workbook.getSheet(0);
    Cell readCell = sheet.getCell(column, row); //read format from another cell(if you want to copy its existing properties otherwise you can ignore).
    WritableCellFormat cellFormatObj = new WritableCellFormat(
                        noBoldFont);
    CellFormat readFormat = readCell.getCellFormat() == null ? cellFormatObj
                        : readCell.getCellFormat();
    newFormat = new WritableCellFormat(readFormat);
    newFormat.setBackground(Colour.WHITE);
    newFormat.setBorder(jxl.format.Border.BOTTOM,jxl.format.BorderLineStyle.THIN);
    newFormat.setAlignment(Alignment.CENTRE);
    

    Step 3: when you create a new cell(or add a cell with particular format in excel), add the format as a parameter. newFormat(WritableCellFormat objecT) will the new format which you want to set.

    WritableSheet s = workbook.getSheet(0);
     //column, row , where you wan the new format , note newFormat is passed as parameter.
    s.addCell(new Label(column, row, request.getRuleId(), copyCellFormat(s, column,
                        newFormat))); 
    

    Imports required for the above operation.

    import jxl.Cell;
    import jxl.Workbook;
    import jxl.format.Alignment;
    import jxl.format.CellFormat;
    import jxl.format.Colour;
    import jxl.format.VerticalAlignment;
    import jxl.write.Label;
    import jxl.write.WritableCellFormat;
    import jxl.write.WritableFont;
    import jxl.write.WritableSheet;
    import jxl.write.WritableWorkbook;