2

How do I print an excel Workbook without having it open in the background, using Java?

Please note that I need to print all the sheets, not just the active one.

I have tried things like Desktop.print(FileName); but that doesn't seem to work for all the sheets.

I am using the Apache POI API to create Excel files through Java.

Many thanks!

UPDATE

To explain my problem a little more, I am using Apace POI to print the Excel file as -

HSSFSheet sheet = workbook.getSheet("Sheet5"); 
HSSFRow row21 = sheet.getRow((short)5);
        row21.getCell((short)2).setCellValue(notcorrect);
        desktop.print(new File(filename));

        HSSFSheet sheet7 = workbook.getSheet("Sheet7");

        HSSFRow row20 = sheet7.getRow((short)3);
        row20.getCell((short)2).setCellValue(logreference);
        row20.getCell((short)4).setCellValue(ISSUENUMBER);
        desktop.print(new File(filename));

        HSSFSheet sheet8 = workbook.getSheet("Sheet8");
        HSSFRow row22 = sheet8.getRow((short)3);
        row22.getCell((short)2).setCellValue(logreference);
        row22.getCell((short)4).setCellValue(ISSUENUMBER);
desktop.print(new File(filename));

But this seems to work only for the active workbook. If I have a workbook in my Excel file as the following -

enter image description here

The code above will only print the active sheet i.e. sheet # 5. How do I use Jexcel to print Sheet 5, 6 AND 7?

Many thanks!

TheLuminor
  • 1,411
  • 3
  • 19
  • 34

1 Answers1

0

Before writing code we have to download apache-poi jars https://poi.apache.org/download.html Download - poi-bin-5.0.0-20210120.tar.gz (current version)

package test1;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class P1 {

    public static void main(String[] args) throws IOException {
        
        //Path to excel from system = /Users/user/Downloads/test1.xlsx"
        File f = new File("/Users/user/Downloads/test1.xlsx");
        FileInputStream fis = new FileInputStream(f);
        XSSFWorkbook wb = new XSSFWorkbook(fis);

        //June2021 is my sheet name of excel
        XSSFSheet sheet = wb.getSheet("June2021");
        
        int RowCount = sheet.getLastRowNum() - sheet.getFirstRowNum();
        for(int i=0; i<= RowCount; i++) {
            System.out.print("Row "+ i + " data is : ");
            int cellCount = sheet.getRow(i).getLastCellNum();
            
            for(int j=0; j<cellCount; j++) {
                XSSFCell c1 = sheet.getRow(i).getCell(j);
                System.out.print(c1 + " ");
            }
            System.out.println();
        }
    }
}