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

3
apache-poi-2/.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
*.docx
temp.xls
temp.xlsx

24
apache-poi-2/pom.xml Normal file
View File

@ -0,0 +1,24 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>apache-poi</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>apache-poi</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.0.0</version>
</dependency>
</dependencies>
</project>

View File

@ -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);
}
}
}

View File

@ -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.