<!-- csv文件解析依赖 -->
<dependency>
<groupId>com.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>5.4</version>
</dependency>
<!-- 大exce -->
<dependency>
<groupId>com.monitorjbl</groupId>
<artifactId>xlsx-streamer</artifactId>
<version>2.1.0</version>
</dependency>
import org.apache.poi.ss.usermodel.*;
public final static String NEW_LINE = "\r\n";
public static void convertXlsToCsv(String sourcePath, String targetPath,String splitSymbol){
FileInputStream in = null;
try {
in = new FileInputStream(new File(sourcePath));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Workbook wk = StreamingReader.builder()
.rowCacheSize(100)
.bufferSize(2048)
.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) ? "" : splitSymbol;
if(cell == null){
fileBuilder.append(" "+ tmp);
}else {
fileBuilder.append(getFilterSpecitalChar(cell.getStringCellValue()) + tmp);
}
}
fileBuilder.append(NEW_LINE);
count++;
}
}
System.out.println("Count: " + count);
String res = fileBuilder.toString();
try {
File targetFile = new File(targetPath);
if(!targetFile.exists()){
targetFile.createNewFile();
}
Files.write(res.getBytes(StandardCharsets.UTF_8), targetFile);
}catch (Exception e){
e.printStackTrace();
}
finally {
try {
if(in != null)in.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
public static String getFilterSpecitalChar(String str){
String regEx="[^0-9a-zA-Z\\u4E00-\\u9FA5\\u002A]";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(str);
return m.replaceAll("").trim();
}