Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems fitting sheet to a single page in xlsx files using the Apache POI library

I'm trying to create some xlsx files using the Apache POI library for Java and everything to create the files is working fine.

The problem comes when I want to print those files using a physical printer. I want to make each sheet in my workbooks fit to a single page. I looked around in the documentation and the following code would be supposed to work:

       XSSFWorkbook wb = new XSSFWorkbook();
       XSSFSheet sheet = wb.createSheet("format sheet");

       PrintSetup ps = sheet.getPrintSetup();

       sheet.setAutobreaks(true);

       ps.setFitHeight((short)1);
       ps.setFitWidth((short)1);

       for(int i = 0; i < 100; ++i){
            sheet.createRow(i);
            sheet.getRow(i).createCell(0).setCellValue("Test " + i);
        }

       FileOutputStream output = new FileOutputStream("Test.xlsx");
       wb.write(output);
       output.close();

But it doesn't... When I try to print it, it prints to three sheets (what it would actually be supposed to print on if I didn't use the PrintSetup part). So the code just doesn't do anything at all.

Can anyone tell me what is wrong with that code?

Also, I have another question about printing xlsx files: I want to know if there's a way to print the xlsx files from my Java program without actually opening the files and clicking on print? Like wb.printAllSheetsInWorkbook(); or something like that.

like image 763
Adam Smith Avatar asked Apr 09 '12 01:04

Adam Smith


1 Answers

After

ps.setFitHeight((short)1);
ps.setFitWidth((short)1);

Use

sheet.setFitToPage(true);
like image 73
Dan Avatar answered Oct 21 '22 20:10

Dan