Read an excel file in java excluding the first row

880 Views Asked by At

I'm trying to automatically create reports from a JasperReport template that uses xlsx files, the method I'm using to read from the excel file is this :

String[] columnNames = new String[]{"arg1", "arg2", "arg3", "arg4", "arg5"};
int[] columnIndexes = new int[]{0, 1, 2, 3, 4};
ds = new JRXlsxDataSource(JRLoader.getLocationInputStream("../Book2.xlsx"));
            ds.setColumnNames(columnNames, columnIndexes);

But the problem is, the excel file should only contain data and I should manually determine columns, my question is how to read the columns directly from the first row and then input the rest of the file to JRXlsxDataSource method (If it isn't excluded then it will generate a type error, expecting Long but getting String instead) ? Thank you

UPDATE : I've tried to get first row and then delete it but I can't save the file because POI avoids making modifications to the file :

public static void removeRow(HSSFSheet sheet, int rowIndex) {
    int lastRowNum = sheet.getLastRowNum();
    if (rowIndex >= 0&&rowIndex < lastRowNum) {
        sheet.shiftRows(rowIndex + 1, lastRowNum, -1);
    }
    if (rowIndex == lastRowNum) {
        HSSFRow removingRow = sheet.getRow(rowIndex);
        if(removingRow != null) {
            sheet.removeRow(removingRow);
        }
    }
}

public static String[] getRow(HSSFSheet sheet) {
    String[] values = null;
    for (int i = 0; i < 5; i++) {
        values[i] = sheet.getRow(0).getCell(0).toString();  
    }
    return values;      
}
0

There are 0 best solutions below