Total Pageviews

2016/09/08

[Apache POI] How to freeze the first row

Problem
I am using Apache POI to write data into Microsoft Excel. 
If I would like to keep the first row on the top of this document when I scroll down, how to do it?


How-to
You can utilize createFreezePane API which provide by Apache POI to fulfill this requirement. Here has code snippet:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
 @Override
 public File exportIssuesToXls(List < Issue > issues) throws IOException, RedmineException {
  Workbook workbook = new HSSFWorkbook();
  Sheet sheet = workbook.createSheet("issue list");
  CellStyle style = createCellStyle(workbook);

  //....

  //freeze the first row
  sheet.createFreezePane(0, 1);

  FileOutputStream outputStream = null;
  File tmpFile = null;
  try {
   tmpFile = File.createTempFile("issue", ".xls");
   log.info("tmpFile = " + tmpFile.getCanonicalPath());
   outputStream = new FileOutputStream(tmpFile);
   workbook.write(outputStream);

  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } finally {
   if (outputStream != null) {
    outputStream.close();
   }
   if (workbook != null) {
    workbook.close();
   }
  }
  return tmpFile;
 }



Reference
[1] https://stackoverflow.com/questions/17932575/apache-poi-locking-header-rows

No comments: