用apache poi xlsx到csv转换器Java

时间:2014-09-29 14:26:00

标签: java excel apache csv xlsx

您好我的问题是基于此Question。 到目前为止这是我的版本

    package converters;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Iterator;

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 XlsxtoCSV {

    public static void main(String[] args) {

        File inputFile = new File(
                "C:\\Users\\USR\\Desktop\\testExport.xlsx");
        File outputFile = new File("C:\\Users\\USR\\Desktop\\output.csv");
        xlsx(inputFile, outputFile);
    }

    static void xlsx(File inputFile, File outputFile) {
        String seperator = ";";
        // For storing data into CSV files
        StringBuffer data = new StringBuffer();
        try {
            FileOutputStream fos = new FileOutputStream(outputFile);

            // Get the workbook object for XLSX file
            XSSFWorkbook wBook = new XSSFWorkbook(
                    new FileInputStream(inputFile));

            // Get first sheet from the workbook
            XSSFSheet sheet = wBook.getSheetAt(0);
            Row row;
            Cell cell;

            // Iterate through each rows from first sheet
            Iterator<Row> rowIterator = sheet.iterator();
            int i = 0; //I need 11 columns wich can be empty
            while (i < 11) {
                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:
                        data.append(cell.getBooleanCellValue() + seperator);

                        break;
                    case Cell.CELL_TYPE_NUMERIC:
                        data.append(cell.getNumericCellValue() + seperator);

                        break;
                    case Cell.CELL_TYPE_STRING:
                        data.append(cell.getStringCellValue() + seperator);

                        break;

                    case Cell.CELL_TYPE_BLANK:
                        data.append("" + seperator);
                        break;
                    default:
                        data.append(cell + seperator);

                    }
                }
                data.append("\r\n");
                i++;
            }

            fos.write(data.toString().getBytes());
            fos.close();
            System.out.println(data.toString());
        } catch (Exception ioe) {
            ioe.printStackTrace();
        }
    }
}

但我的问题是,如果一个单元格中有一个换行符,它就不会起作用,对我来说很重要。有帮助吗?我需要它完全像你&#34;保存为csv&#34;在excel中

0 个答案:

没有答案