Gideon
Gideon

Reputation: 1547

Set default print scalling for the generated Excel file in Apache POI

I generate an Excel file via Apache POI successfully. The problem is that, when I try to print it, the last 3 columns is not within the printable area. For example, the worksheet has columns A to L but it only fits column A to when printing. The users always change the print scaling from "No Scaling" to "Fit All Columns on One Page" before printing.

enter image description here

How can I modify the Excel file in such a way that all columns would fit on the printable area, and the users won't need to change the scaling every time they print.

Upvotes: 4

Views: 4095

Answers (1)

Axel Richter
Axel Richter

Reputation: 61890

This can be done with a combination of Sheet.setFitToPage and PrintSetup.setFitWidth and PrintSetup.setFitHeight.

Example:

import java.io.*;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;

public class PrintSetupFitWidth {

 public static void main(String[] args) throws Exception {
  Workbook workbook = new XSSFWorkbook();
  Sheet sheet = workbook.createSheet();

  //create at least one cell so print preview is possible
  sheet.createRow(0).createCell(0).setCellValue("Cell A1");

  //set page setup to fit to one page width but multiple pages height
  sheet.setFitToPage(true);
  sheet.getPrintSetup().setFitWidth((short)1);
  sheet.getPrintSetup().setFitHeight((short)0);

  FileOutputStream fileOut = new FileOutputStream("PrintSetupFitWidth.xlsx");
  workbook.write(fileOut);
  fileOut.close();
  workbook.close();
 }
}

Upvotes: 6

Related Questions