minhas informações de contato
Correspondência[email protected]
2024-07-12
한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina
Houve um cenário recentemente em que um arquivo csv foi lido no servidor ftp e colocado no banco de dados, mas alguns dos arquivos fornecidos pelo cliente eram arquivos xls. Então, tivemos que encontrar uma maneira de converter arquivos Excel em csv. começou sem mais delongas.
public static void convertExcelToCSV(String excelFilePath, String csvFilePath) throws IOException {
FileInputStream inputStream = new FileInputStream(excelFilePath);
Workbook workbook = getWorkbook(inputStream, excelFilePath);
inputStream.close();
FileWriter writer = new FileWriter(csvFilePath);
for (int sheetIndex = 0; sheetIndex < workbook.getNumberOfSheets(); sheetIndex++) {
Sheet sheet = workbook.getSheetAt(sheetIndex);
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
StringBuilder stringBuilder = new StringBuilder();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
stringBuilder.append(getCellValue(cell));
if (cellIterator.hasNext()) {
stringBuilder.append(",");
}
}
writer.write(stringBuilder.toString() + "n");
}
if (sheetIndex < workbook.getNumberOfSheets() - 1) {
writer.write("n"); // 在不同工作表之间添加一个空行
}
}
writer.flush();
writer.close();
workbook.close();
}
private static Workbook getWorkbook(FileInputStream inputStream, String excelFilePath) throws IOException {
Workbook workbook = null;
if (excelFilePath.endsWith("xlsx")) {
workbook = new XSSFWorkbook(inputStream);
} else if (excelFilePath.endsWith("xls")) {
workbook = new HSSFWorkbook(inputStream);
} else {
throw new IllegalArgumentException("The specified file is not an Excel file");
}
return workbook;
}
private static String getCellValue(Cell cell) {
//DataFormatter formatter = new DataFormatter();
String formatPattern = "yyyy-MM-dd HH:mm:ss"; // 自定义日期时间格式
//FormulaEvaluator evaluator = cell.getSheet().getWorkbook().getCreationHelper().createFormulaEvaluator();
switch (cell.getCellType()) {
case STRING:
return cell.getRichStringCellValue().getString();
case NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
Date date = cell.getDateCellValue();
DateFormat dateFormat = new SimpleDateFormat(formatPattern);
return dateFormat.format(date);
} else {
return Double.toString(cell.getNumericCellValue());
}
case BOOLEAN:
return Boolean.toString(cell.getBooleanCellValue());
case FORMULA:
return cell.getCellFormula();
default:
return "";
}
}
public static void main(String[] args) {
String excelFilePath = "D:\我是excel文件.xlsx";
String csvFilePath = "D:\我是csv文件.csv";
try {
convertExcelToCSV(excelFilePath, csvFilePath);
System.out.println("Excel file converted to CSV successfully!");
} catch (IOException e) {
e.printStackTrace();
}
}
O acima é a integração保留时间格式
Todos os códigos necessários, o teste pessoal é muito fácil de usar!