POM
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-csv</artifactId> <version>1.8</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>YOUR_POI_VERSION</version> </dependency>
工具类
import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVPrinter; import org.apache.poi.ss.usermodel.*; import java.io.File; import java.io.FileWriter; public class ExcelToCSV { public static void change(String excelFilePath, String csvFilePath) throws Exception { Workbook workbook = WorkbookFactory.create(new File(excelFilePath)); Sheet sheet = workbook.getSheetAt(0); // 获取第一个Sheet try ( FileWriter fileWriter = new FileWriter(csvFilePath); CSVPrinter csvPrinter = new CSVPrinter(fileWriter, CSVFormat.DEFAULT) ) { for (Row row : sheet) { String[] columns = row.iterator().hasNext() ? new String[row.getLastCellNum()] : new String[0]; int i = 0; for (Cell cell : row) { columns[i++] = getCellValueAsString(cell); } csvPrinter.printRecord(columns); } } } private static String getCellValueAsString(Cell cell) { switch (cell.getCellTypeEnum()) { case STRING: return cell.getStringCellValue(); case NUMERIC: return String.valueOf(cell.getNumericCellValue()); case BOOLEAN: return String.valueOf(cell.getBooleanCellValue()); case FORMULA: return cell.getCellFormula(); default: return ""; } } }
标签:小而,return,String,EXCEL,美的,cell,new,apache,import From: https://www.cnblogs.com/pangyangqi/p/18089687