11
11
import java .util .stream .Collectors ;
12
12
import java .util .stream .IntStream ;
13
13
import org .apache .commons .lang3 .StringUtils ;
14
+ import org .apache .poi .ss .usermodel .Cell ;
15
+ import org .apache .poi .ss .usermodel .CellStyle ;
16
+ import org .apache .poi .ss .usermodel .CellType ;
14
17
import org .apache .poi .ss .usermodel .Row ;
15
18
import org .apache .poi .ss .usermodel .Row .MissingCellPolicy ;
16
19
import org .apache .poi .ss .usermodel .Sheet ;
@@ -45,9 +48,14 @@ public static String toCSV(InputStream inputStream) throws IOException {
45
48
int lastCellNum = row .getLastCellNum () - 1 ;
46
49
return IntStream .rangeClosed (0 , lastCellNum )
47
50
.mapToObj (
48
- cn ->
49
- row .getCell (cn , MissingCellPolicy .CREATE_NULL_AS_BLANK )
50
- .getStringCellValue ())
51
+ cn -> {
52
+ Cell cell = row .getCell (cn , MissingCellPolicy .CREATE_NULL_AS_BLANK );
53
+ if (cell .getCellType () == CellType .NUMERIC ) {
54
+ return String .valueOf ((int ) cell .getNumericCellValue ());
55
+ } else {
56
+ return cell .getStringCellValue ();
57
+ }
58
+ })
51
59
.collect (Collectors .toList ());
52
60
})
53
61
.collect (Collectors .toList ());
@@ -72,13 +80,24 @@ public static InputStream fromCSV(String csvString) throws IOException {
72
80
ByteArrayOutputStream baos = new ByteArrayOutputStream ();
73
81
try (Workbook wb = new XSSFWorkbook ()) {
74
82
Sheet sheet = wb .createSheet ();
83
+ CellStyle numberCellStyle = wb .createCellStyle ();
84
+ numberCellStyle .setDataFormat ((short ) 1 );
75
85
76
- List <String > line ;
86
+ List <String > columns ;
77
87
int rowNo = 0 ;
78
- while ((line = csvListReader .read ()) != null ) {
88
+ while ((columns = csvListReader .read ()) != null ) {
79
89
Row row = sheet .createRow (rowNo ++);
80
90
AtomicInteger cellNo = new AtomicInteger ();
81
- line .forEach (s -> row .createCell (cellNo .getAndIncrement ()).setCellValue (s ));
91
+ columns .forEach (
92
+ s -> {
93
+ Cell cell = row .createCell (cellNo .getAndIncrement ());
94
+ try {
95
+ cell .setCellValue (Integer .parseInt (s ));
96
+ cell .setCellStyle (numberCellStyle );
97
+ } catch (NumberFormatException e ) {
98
+ cell .setCellValue (s );
99
+ }
100
+ });
82
101
}
83
102
84
103
wb .write (baos );
0 commit comments