Java - 读取Excel并转CSV格式
一. 案例
1.pom依赖:
<dependency> <groupId>com.monitorjbl</groupId> <artifactId>xlsx-streamer</artifactId> <version>2.1.0</version> </dependency>
2.读取Excel并转化为csv格式:
// Excel文件地址 public final static String PATH = "xxx"; // 输出的地址 public final static String OUT = "xxx"; // 换行 public final static String NEW_LINE = " "; public static void test(File file) throws Exception { FileInputStream in = new FileInputStream(file); Workbook wk = StreamingReader.builder() .rowCacheSize(100) .bufferSize(4096) .open(in); int sheetNums = wk.getNumberOfSheets(); int count = 0; StringBuilder fileBuilder = new StringBuilder(); for (int i = 0; i < sheetNums; i++) { StreamingSheet sheet = (StreamingSheet) wk.getSheetAt(i); // 遍历所有的行 for (Row row : sheet) { // 遍历所有的列 int size = ((StreamingRow) row).getCellMap().size(); for (int col = 0; col < size; col++) { StreamingCell cell = (StreamingCell) row.getCell(col); String tmp = (col == size - 1) ? "" : ","; fileBuilder.append(cell.getStringCellValue() + tmp); } // 换行 fileBuilder.append(NEW_LINE); count++; } } System.out.println("Count: " + count); String res = fileBuilder.toString(); try { Files.write(Paths.get(OUT), res.getBytes(StandardCharsets.UTF_8)); } finally { in.close(); } }
3.测试,准备一个excel表格: 4.修改下文件地址和输出,运行程序后,结果如下: csv格式的文件:
下一篇:
C/C++省略符形参原理和使用