BAEL-5205 Adding a column to an Excel file using Apache POI (#11491)

* BAEL-5205 Adding a column to an Excel file using Apache POI

* BAEL-5205 move the test xls file into the test folder

Co-authored-by: Gang Wu <wugagnca@hotmail.com>
This commit is contained in:
wugangca
2021-11-28 08:51:13 -07:00
committed by GitHub
parent 1af458be34
commit 9461caeb27
5 changed files with 83 additions and 0 deletions
@@ -0,0 +1,16 @@
package com.baeldung.poi.excel.newcolumn;
import org.apache.poi.ss.usermodel.CellType;
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.xssf.usermodel.XSSFWorkbook;
public class ExcelColumn {
public void addColumn(Sheet sheet, CellType cellType) {
for (Row currentRow : sheet) {
currentRow.createCell(currentRow.getLastCellNum(), cellType);
}
}
}
@@ -0,0 +1,40 @@
package com.baeldung.poi.excel.newcolumn;
import org.apache.poi.ss.usermodel.CellType;
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.xssf.usermodel.XSSFWorkbook;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Paths;
import static org.junit.Assert.assertEquals;
public class ExcelColumnUnitTest {
private static final String FILE_NAME = "newColumnTest.xlsx";
private String fileLocation;
@Before
public void setup() throws URISyntaxException {
fileLocation = Paths.get(ClassLoader.getSystemResource(FILE_NAME).toURI()).toString();
}
@Test
public void givenExistingRows_whenAddNewColumn_thenRowColumnNumberIncreased() throws IOException {
Workbook workbook = new XSSFWorkbook(fileLocation);
Sheet sheet = workbook.getSheetAt(0);
Row row = sheet.getRow(0);
assertEquals(5, row.getLastCellNum());
ExcelColumn excelColumn = new ExcelColumn();
excelColumn.addColumn(sheet, CellType.STRING);
assertEquals(6, row.getLastCellNum());
workbook.close();
}
}
Binary file not shown.