在Java中将.xls转换为.csv

时间:2014-04-10 17:23:23

标签: java csv apache-poi

我想将xls文件转换为csv。我成功将其转换为csv文件,但最后一列也附加了逗号。如何删除最后一个逗号,例如1,2,2,3,......你能帮忙吗?

package bwtest;

import java.io.*;
import java.util.Iterator;


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;

class ExcelToCSV {

    static void convertToXlsx(File inputFile, File outputFile) {
        // For storing data into CSV files
        StringBuffer cellValue = new StringBuffer();
        try {
            FileOutputStream fos = new FileOutputStream(outputFile);

            // Get the workbook instance for XLSX file
            XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(inputFile));

            // Get first sheet from the workbook
            XSSFSheet sheet = wb.getSheetAt(0);

            Row row;
            Cell cell;

            // Iterate through each rows from first sheet
            Iterator<Row> rowIterator = sheet.iterator();

            while (rowIterator.hasNext()) {
                row = rowIterator.next();

                // For each row, iterate through each columns


                Iterator<Cell> cellIterator = row.cellIterator();

                while (cellIterator.hasNext()) {

                    cell = cellIterator.next();


                    switch (cell.getCellType()) {


                    case Cell.CELL_TYPE_BOOLEAN:

                        cellValue.append(cell.getBooleanCellValue() + ",");
                        break;


                    case Cell.CELL_TYPE_NUMERIC:

                        cellValue.append(cell.getNumericCellValue() 
+ ",");

                        break;

                    case Cell.CELL_TYPE_STRING:
                        cellValue.append(cell.getStringCellValue() + ",");
                        break;

                    case Cell.CELL_TYPE_BLANK:
                        cellValue.append("" + ",");
                        break;

                    default:
                        cellValue.append(cell + ",");

                    }
                }
            }

            fos.write(cellValue.toString().getBytes());
            fos.close();

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

    static void convertToXls(File inputFile, File outputFile) {
        // For storing data into CSV files
        StringBuffer cellDData = new StringBuffer();
        try {
            FileOutputStream fos = new FileOutputStream(outputFile);

            // Get the workbook instance for XLS file
            HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(
                    inputFile));
            // Get first sheet from the workbook
            HSSFSheet sheet = workbook.getSheetAt(0);
            Cell cell;
            Row row;

            // Iterate through each rows from first sheet
            Iterator<Row> rowIterator = sheet.iterator();
            while (rowIterator.hasNext()) {
                row = rowIterator.next();

                // For each row, iterate through each columns
                Iterator<Cell> cellIterator = row.cellIterator();
                while (cellIterator.hasNext()) {
                    cell = cellIterator.next();

                    switch (cell.getCellType()) {

                    case Cell.CELL_TYPE_BOOLEAN:
                        cellDData.append(cell.getBooleanCellValue() + ",");
                        break;

                    case Cell.CELL_TYPE_NUMERIC:
                        cellDData.append(cell.getNumericCellValue() + ",");
                        break;

                    case Cell.CELL_TYPE_STRING:
                        cellDData.append(cell.getStringCellValue() + ",");
                        break;

                    case Cell.CELL_TYPE_BLANK:
                        cellDData.append("" + ",");
                        break;

                    default:
                        cellDData.append(cell + ",");
                    }
                }
            }

            fos.write(cellDData.toString().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) 
{

        File inputFile = new File("C:\input.xls");

       File outputFile = new File("C:\output1.csv");

        File inputFile2 = new File("C:\input.xlsx");

        File outputFile2 = new File("C:\output2.csv");

        convertToXls(inputFile, outputFile);

        convertToXlsx(inputFile2, outputFile2);
}
}

3 个答案:

答案 0 :(得分:1)

假设每一行都有单元格:

在cellIterator循环之后和rowIterator循环完成之前,添加:

cellDData.deleteCharAt(cellDData.length()-1);

这应删除该行中的最后一个逗号。

如果可能有一行cellIterator没有运行(我怀疑),那么你可以将boolean hasCells = false;放在cellIterator循环之前,并在里面设置hasCells = true;某处的循环然后,只删除逗号if(hasCells)

答案 1 :(得分:0)

您的转化算法不正确。 而不是添加值,然后逗号, 你应该添加逗号(如果需要)然后添加值。 这是一些代码:

...
int columnNumber = 1;
while (cellIterator.hasNext())
{
    if (columnNumber > 1)
    {
        cellValue.append(",")
    }

    row = rowIterator.next();

    switch (cell.getCellType())
    {
         ... append the cell value to the cellValue.
    }

    ++columnNumber;
}
...

答案 2 :(得分:-1)

在每行之后,您需要插入换行符&#34; / r / n&#34;并删除最后一个昏迷。 你可以在那时把它写到fos上。

if (cellDData != null && cellDData.length() > 1) {
   String cellDDataString = cellDData.toString();
   cellDDataString = cellDDataString.substring(0,cellDDataString.length() - 1) + "/r/n";
   fos.write(cellDDataString);
}
cellDData = new StringBuffer();