2
2
import org .apache .poi .ss .usermodel .*;
3
3
import org .apache .poi .xssf .usermodel .XSSFWorkbook ;
4
4
5
+ import java .io .File ;
5
6
import java .io .FileOutputStream ;
6
7
import java .io .IOException ;
7
8
import java .util .ArrayList ;
@@ -37,7 +38,10 @@ public class ExcelWriter {
37
38
public static void main (String [] args ) throws IOException , InvalidFormatException {
38
39
39
40
// Create a Workbook
40
- Workbook workbook = new XSSFWorkbook ();
41
+ Workbook workbook = new XSSFWorkbook (); // new HSSFWorkbook() for generating `.xls` file
42
+
43
+ /* CreationHelper helps us create instances for various things like
44
+ DataFormat, Hyperlink, RichTextString etc in a format (HSSF, XSSF) independent way */
41
45
CreationHelper createHelper = workbook .getCreationHelper ();
42
46
43
47
// Create a Sheet
@@ -78,14 +82,15 @@ public static void main(String[] args) throws IOException, InvalidFormatExceptio
78
82
row .createCell (1 )
79
83
.setCellValue (employee .getEmail ());
80
84
81
- Cell dobCell = row .createCell (2 );
82
- dobCell .setCellValue (employee .getDateOfBirth ());
83
- dobCell .setCellStyle (dateCellStyle );
85
+ Cell dateOfBirthCell = row .createCell (2 );
86
+ dateOfBirthCell .setCellValue (employee .getDateOfBirth ());
87
+ dateOfBirthCell .setCellStyle (dateCellStyle );
84
88
85
89
row .createCell (3 )
86
90
.setCellValue (employee .getSalary ());
87
91
}
88
92
93
+ // Resize all columns to fit the content size
89
94
for (int i = 0 ; i < columns .length ; i ++) {
90
95
sheet .autoSizeColumn (i );
91
96
}
@@ -95,6 +100,35 @@ public static void main(String[] args) throws IOException, InvalidFormatExceptio
95
100
workbook .write (fileOut );
96
101
fileOut .close ();
97
102
}
103
+
104
+
105
+ // Example to modify an existing excel file
106
+ private static void modifyExistingWorkbook () throws InvalidFormatException , IOException {
107
+ // Obtain a workbook from the excel file
108
+ Workbook workbook = WorkbookFactory .create (new File ("existing-spreadsheet.xlsx" ));
109
+
110
+ // Get Sheet at index 0
111
+ Sheet sheet = workbook .getSheetAt (0 );
112
+
113
+ // Get Row at index 1
114
+ Row row = sheet .getRow (1 );
115
+
116
+ // Get the Cell at index 2 from the above row
117
+ Cell cell = row .getCell (2 );
118
+
119
+ // Create the cell if it doesn't exist
120
+ if (cell == null )
121
+ cell = row .createCell (2 );
122
+
123
+ // Update the cell's value
124
+ cell .setCellType (CellType .STRING );
125
+ cell .setCellValue ("Updated Value" );
126
+
127
+ // Write the output to a file
128
+ FileOutputStream fileOut = new FileOutputStream ("existing-spreadsheet.xlsx" );
129
+ workbook .write (fileOut );
130
+ fileOut .close ();
131
+ }
98
132
}
99
133
100
134
0 commit comments