Creating a header and footer for a worksheet

In this post under Apache excel, I will show with example how to add header and footer to an Worksheet.

Below is the complete code for your reference.

Main Class


1  package package5;
2  
3  import java.io.BufferedReader;
4  import java.io.File;
5  import java.io.FileOutputStream;
6  import java.io.FileReader;
7  import java.io.IOException;
8  
9  import org.apache.poi.xssf.usermodel.XSSFCell;
10 import org.apache.poi.xssf.usermodel.XSSFRow;
11 import org.apache.poi.xssf.usermodel.XSSFSheet;
12 import org.apache.poi.xssf.usermodel.XSSFWorkbook;
13 
14 public class Example5 {
15     public static void main(String[] args) throws IOException {
16         File outputFile = new File("Example4.xlsx");
17         File inputFile = new File("Input1.txt");
18         try(XSSFWorkbook workbook = new XSSFWorkbook();
19             FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
20             FileReader fileReader = new FileReader(inputFile);
21             BufferedReader bufferedReader = new BufferedReader(fileReader)) {
22             XSSFSheet xssfSheet = workbook.createSheet("Page1");
23             xssfSheet.getHeader().setCenter("Welcome To Header");
24             String line = bufferedReader.readLine();
25             int rowNumber = 0;
26             while(line != null) {
27                 XSSFRow xssfRow = xssfSheet.createRow(rowNumber);
28                 String[] columns = line.split(",");
29                 for(int j = 0; j < columns.length; j++) {
30                     XSSFCell xssfCell = xssfRow.createCell(j);
31                     xssfCell.setCellValue(columns[j]);
32                 }
33                 line = bufferedReader.readLine();
34                 rowNumber++;
35             }
36             xssfSheet.getFooter().setCenter("Welcome To Footer");
37             workbook.write(fileOutputStream);
38         }
39     }
40 }

In the above code, at line 23, we call the “getHeader()” method to get the excel sheet header instance.

In the same line with the help of method chaining, we are calling “setCenter()” method on the “Header” instance and passing the actual header string.

Similarly, at line 36, we call the “getFooter()” method to get the excel sheet footer instance.

In the same line with the help of method chaining, we are calling “setCenter()” method on the “Footer” instance and passing the actual footer String.

In this way we can add header and footer to an excel sheet.

Leave a Reply