问题
I have convert .xls to csv file.my code is woring fine.but one issue,I was facing.like some cell value has (xxx,Md) these cell value should consider one value but take two column.how to rectify the problem here ,I have attached my code.
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;
}
}
}
}
回答1:
You can write your own code, but I would advise to use a library like SuperCSV or OpenCSV
For CSV itself, there is RFC-4180. This RFC defines what 'proper' CSV should look like; it tells you how and what to quote and escape
回答2:
I could think of the following two options:
- Change the separator from COMMA to something else (PIPE maybe ?)
- Wrap your strings into inverted commas ("")
Sample code ...
case Cell.CELL_TYPE_STRING:
String out=cell.getRichStringCellValue().getString();
if(out.contains(",")) {
out = "\""+out+"\"";
}
cellDData.append(out + ",");
System.out.println("string"+out);
break;
P.S: You may use Strnigbuilder instead of string concatenation
回答3:
According to RFC-4180, Each field may or may not be enclosed in double quotes. So, if you enclose, each cell value within double quotes, comma's in between will not be considered as delimiters. If you are following this approach, make sure to escape any double quotes appearing inside a field by preceding it with another double quote.
来源:https://stackoverflow.com/questions/23781826/convert-xls-to-csv-file-using-apache-poi