org.opentestsystem.delivery.testreg.upload.ExcelFileAppender.java Source code

Java tutorial

Introduction

Here is the source code for org.opentestsystem.delivery.testreg.upload.ExcelFileAppender.java

Source

/*******************************************************************************
 * Educational Online Test Delivery System
 * Copyright (c) 2013 American Institutes for Research
 * 
 * Distributed under the AIR Open Source License, Version 1.0
 * See accompanying file AIR-License-1_0.txt or at
 * http://www.smarterapp.org/documents/American_Institutes_for_Research_Open_Source_Software_License.pdf
 ******************************************************************************/

package org.opentestsystem.delivery.testreg.upload;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

public class ExcelFileAppender implements FileAppender {

    public InputStream insertAtTop(String text, InputStream inputStream) {
        try {
            final Workbook workbook = WorkbookFactory.create(inputStream);
            Sheet sheet = workbook.getSheetAt(0);
            sheet.shiftRows(0, sheet.getLastRowNum(), 1);
            Row formatTypeRow = sheet.createRow(0);
            formatTypeRow.createCell(0, Cell.CELL_TYPE_STRING).setCellValue(text);
            return new ByteArrayInputStream(new ByteArrayOutputStream() {
                {
                    workbook.write(this);
                }
            }.toByteArray());
        } catch (InvalidFormatException | IOException e) {
            throw new RuntimeException("");
        }
    }
}