使用apache poi将.xls转换为csv文件

我已经将.xls转换为csv file.my代码是很好的。但是有一个问题,我正面临着像某些单元格值(xxx,Md)这些单元格值应该考虑一个值,但需要两列。如何纠正问题在这里,我附上我的代码。

try { FileOutputStream fos = new FileOutputStream(outputFile); HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(inputFile)); workbook.setMissingCellPolicy(Row.CREATE_NULL_AS_BLANK); HSSFSheet sheet = workbook.getSheetAt(0); for(int rowIndex = sheet.getFirstRowNum(); rowIndex <= sheet.getLastRowNum(); rowIndex++) { Cell cell=null; Row row = null; int previousCell = -1; int currentCell = 0; row = sheet.getRow(rowIndex); for(int colIndex=row.getFirstCellNum(); colIndex < row.getLastCellNum(); colIndex++) { cell = row.getCell(colIndex); currentCell = cell.getColumnIndex(); /* Cell processing starts here*/ System.out.println("coll"+colIndex); switch (cell.getCellType()) { case Cell.CELL_TYPE_BOOLEAN: cellDData.append(cell.getBooleanCellValue() + ","); System.out.println("boo"+ cell.getBooleanCellValue()); break; case Cell.CELL_TYPE_NUMERIC: if (DateUtil.isCellDateFormatted(cell)) { SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); String strCellValue = dateFormat.format(cell.getDateCellValue()); cellDData.append(strCellValue +","); } else { System.out.println(cell.getNumericCellValue()); Double value = cell.getNumericCellValue(); Long longValue = value.longValue(); String strCellValue1 = new String(longValue.toString()); cellDData.append(strCellValue1 +","); } break; case Cell.CELL_TYPE_STRING: String out=cell.getRichStringCellValue().getString(); cellDData.append(cell.getRichStringCellValue().getString() + ","); System.out.println("string"+cell.getStringCellValue()); break; case Cell.CELL_TYPE_BLANK: cellDData.append("" +","); System.out.print("THIS IS BLANK"); break; default: break; } } } } 

你可以编写你自己的代码,但我build议使用像SuperCSV或OpenCSV的库

对于CSV本身,有RFC-4180 。 这个RFC定义了什么“正确”的CSV应该看起来像; 它会告诉你如何以及如何引用和逃避

我可以想到以下两个select:

  1. 将分隔符从COMMA更改为其他(PIPE也许?)
  2. 把你的string换成引号(“”)

示例代码…

 case Cell.CELL_TYPE_STRING: String out=cell.getRichStringCellValue().getString(); if(out.contains(",")) { out = "\""+out+"\""; } cellDData.append(out + ","); System.out.println("string"+out); break; 

PS:你可以使用Strnigbuilder而不是string连接