简体   繁体   中英

How to create sheet with right-to-left alignment using Apache POI XSSF

I'm trying to create a sheet in the Excel file using Apache POI.

Since it's Excel 2007, I'm using XSSF and I'm looking a for way to make a sheet right-to-left aligned.

In HSSF there is a method org.apache.poi.hssf.usermodel.HSSFSheet.setRightToLeft(boolean) , but I cannot find it in org.apache.poi.xssf.usermodel.XSSFSheet .

I'm using Apache POI 3.7

The workaround:

 XSSFSheet sheet = workbook.createSheet();
 sheet.getCTWorksheet().getSheetViews().getSheetViewArray(0).setRightToLeft(true);

Source: http://thread.gmane.org/gmane.comp.jakarta.poi.user/17099/focus=17110

As it's not there, you'll need to do a little bit of work, sorry...

First, create a simple file in excel that's left to right. Then, open a copy and set it to right to left in excel, and save. Now, unzip both files (.xlsx is a zip of xml files), and diff the xml to see what changed when right to left was set (I suspect it'll just be /sheets/sheet1.xml that changes BICBW)

Once you know what XML needs changing, short term, grab the low level CT objects from POI and use those to manipulate it. For example, you might get the CTWorkSheet, and set a flag on that

Finally, report a new bug in the POI bugzilla for the missing setter/getter. Upload the two sample files, which can be used in a unit test, and include information on the XML that is changed and the CT objects that need setting. Someone can then quickly add the feature to POI. If you can, include a patch to XSSFSheet that does this too!

You can use reflection if your sheet object is instance of XSSFSheet.

private void setCurrentSheetRtl() {
    try {
        final Field sh = currentSheet.getClass().getDeclaredField("_sh");
        sh.setAccessible(true);
        final XSSFSheet shObj = (XSSFSheet) sh.get(currentSheet);
        final Method method = shObj.getClass().getDeclaredMethod("getSheetTypeSheetViews");
        method.setAccessible(true);
        final CTSheetViews ctSheetViews = (CTSheetViews) method.invoke(shObj);
        ctSheetViews.getSheetViewArray(0).setRightToLeft(true);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM