java 将 .xls 转换为 csv

sak*_*thi 4 java csv excel apache-poi

我已使用 Apache POI 库将 .xls 文件转换为 csv 文件。我迭代每一行和单元格,放置一个逗号,然后附加到缓冲读取器。单元格类型数字和字符串完美转换。如果出现空白单元格,我会输入逗号,但代码不会检测到空白值。怎么做?请帮帮我。

import java.io.*;
import java.util.Iterator;
import java.text.DateFormat;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.math.BigDecimal;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.DateUtil;
class convert {

static void convertToXls(File inputFile, File outputFile)
{
StringBuffer cellDData = new StringBuffer();
String cellDDataString=null;
try
{
        FileOutputStream fos = new FileOutputStream(outputFile);

        HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(inputFile));
        HSSFSheet sheet = workbook.getSheetAt(0);
        Cell cell=null;
        Row row;
        int previousCell;
        int currentCell;
        Iterator<Row> rowIterator = sheet.iterator();
        while (rowIterator.hasNext())
        {
        previousCell = -1;
        currentCell = 0;
        row = rowIterator.next();
         System.out.println("ROW:-->");
        Iterator<Cell> cellIterator = row.cellIterator();
        while (cellIterator.hasNext())
{
          // System.out.println("true" +cellIterator.hasNext());
        cell = cellIterator.next();
        currentCell = cell.getColumnIndex();


        System.out.println("CELL:-->" +cell.toString());
        try{
        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))
                        {

                  //      System.out.println(cell.getDateCellValue());
                        SimpleDateFormat dateFormat = new SimpleDateFormat(
                            "dd/MM/yyyy");
                         String  strCellValue = dateFormat.format(cell.getDateCellValue());
                //      System.out.println("date:"+strCellValue);
                        cellDData.append(strCellValue +",");
                    }
                       else {
                        System.out.println(cell.getNumericCellValue());
                        Double value = cell.getNumericCellValue();
                    Long longValue = value.longValue();
                    String strCellValue1 = new String(longValue.toString());
                //      System.out.println("number:"+strCellValue1);
                         cellDData.append(strCellValue1 +",");
                    }
        //      cellDData.append(cell.getNumericCellValue() + ",");
                //String  i=(new java.text.DecimalFormat("0").format( cell.getNumericCellValue()+"," ));
                //System.out.println("number"+cell.getNumericCellValue());
                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("" + "THIS IS BLANK");
                System.out.print("THIS IS BLANK");
                break;

        default:
                break;
        }}
catch (NullPointerException e) {
                    //do something clever with the exception
                        System.out.println("nullException"+e.getMessage());
                }

}
        int len=cellDData.length() - 1;
//      System.out.println("length:"+len);
//      System.out.println("length1:"+cellDData.length());
       cellDData.replace(cellDData.length() - 1, cellDData.length() , "");
        cellDData.append("\n");
        }
        //cellDData.append("\n");


//String out=cellDData.toString();
//System.out.println("res"+out);

//String o = out.substring(0, out.lastIndexOf(","));
//System.out.println("final"+o);
fos.write(cellDData.toString().getBytes());
//fos.write(cellDDataString.getBytes());
fos.close();

}
catch (FileNotFoundException e)
{
    System.err.println("Exception" + e.getMessage());
}
catch (IOException e)
{
        System.err.println("Exception" + e.getMessage());
}
}

public static void main(String[] args) throws IOException
{
        File inputFile = new File("/bwdev/kadfeb/xls/Accredo_Kadmon_Monthly_02282014.xls");
        File outputFile = new File("output1.csv");
        convertToXls(inputFile, outputFile);
}
Run Code Online (Sandbox Code Playgroud)

Rej*_*eji 5

我假设HSSFWorkbook默认情况下会跳过空白单元格或丢失的单元格。尝试为 HSSFWorkbook 对象设置MissingCellPolicy 。

可以在此处找到为 MissingCellPolicy 设置的可能值

使用行索引和列索引代替迭代器。

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;

       previousCell = -1;
       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*/
            }
    }
Run Code Online (Sandbox Code Playgroud)