My code writes data to excel however it is overwriting the same row and columns. I do not want to overwrite the row that has the column titles and the rows after that if it has data in it.
Steps 1 enter column heading 2 enter data in rows/columns 3 if column heading are there don't write column heading 4 if row/columns filled go to next 5 repeat 1-4
My code is below. Any help would be appreciated.
//Create blank workbook
XSSFWorkbook workbook = new XSSFWorkbook();
//Create a blank sheet
XSSFSheet spreadsheet = workbook.createSheet( " Employee Info ");
//Create row object
XSSFRow row;
//This data needs to be written (Object[])
Map < String, Object[] > clientinfo = new TreeMap < String, Object[] >();
clientinfo.put( "1", new Object[] {
"PayRoll Status", "Week #", "Pay Date","End Date" });
clientinfo.put( "2", new Object[] {
CycleStatus, WeekID, DateId, EndDateId });
//Iterate over data and write to sheet
Set < String > keyid = clientinfo.keySet();
int rowid = 0;
for (String key : keyid) {
row = spreadsheet.createRow(rowid++);
Object [] objectArr = clientinfo.get(key);
int cellid = 0;
for (Object obj : objectArr){
Cell cell = row.createCell(cellid++);
cell.setCellValue((String)obj);
}
}
//Write the workbook in file system
FileOutputStream out = new FileOutputStream(
new File("C:/PayrollSync/Pre-Payroll.xlsx"));
workbook.write(out);
out.close();
System.out.println("Prepayroll.xlsx written successfully");
This is the solution i came up with however it write the count of the rows is there any way to take it off
String excelFilePath = "C://PayrollSync//Pre-Payroll.xlsx";
FileInputStream inputStream = new FileInputStream(new File(excelFilePath));
Workbook workbook = WorkbookFactory.create(inputStream);
Sheet sheet = workbook.getSheetAt(0);
//CycleStatus, WeekID, DateId, EndDateId
Object[][] bookData = {
{CycleStatus,WeekID,DateId,EndDateId},
};
int rowCount = sheet.getLastRowNum();
for (Object[] aBook : bookData) {
Row row = sheet.createRow(++rowCount);
int columnCount = 0;
Cell cell = row.createCell(columnCount);
cell.setCellValue(rowCount);
for (Object field : aBook) {
cell = row.createCell(++columnCount);
if (field instanceof String) {
cell.setCellValue((String) field);
} else if (field instanceof Integer) {
cell.setCellValue((Integer) field);
}
}
}
FileOutputStream outputStream = new FileOutputStream("C://PayrollSync//Pre-Payroll.xlsx");
workbook.write(outputStream);
inputStream.close();
outputStream.close();
> where inner list is "row" and outer list is the list of "rows". So it's only necessary to populate this List
– contrapost Mar 13 '18 at 18:34> with your data.