如何使用apachepoi将Excel xlsx格式转换为java中的csv格式?

时间:2018-08-14 21:20:43

标签: java excel string collections apache-poi

public class ExcelReading {

    public static void echoAsCSV(Sheet sheet) throws IOException {

        XSSFWorkbook wb = new XSSFWorkbook();
        XSSFSheet sheet1= wb.createSheet();

        Row row = null;
        Row row1= null;
        DataFormatter df = new DataFormatter();
        Cell cell;
        Cell cell1;

        for (int i = 0; i < sheet.getLastRowNum(); i++) {
            row = sheet.getRow(i);
            row1=sheet1.createRow(i);
            for (int j = 0; j < row.getLastCellNum(); j++) {
                System.out.print("\"" + row.getCell(j) + "\",");
                cell1 = row1.createCell(j);
                cell1.setCellValue(df.formatCellValue(row.getCell(j)));
            }
            System.out.println();
        }

        FileOutputStream out = new FileOutputStream(new File("C:\\Users\\esatnir\\Videos\\xlsxtocsv\\CH13XC009.csv"));

        wb.write(out);
        out.close();

    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        InputStream inp = null;
        try {
            inp = new FileInputStream("C:\\Users\\esatnir\\Videos\\xlsxtocsv\\CH13XC009_2500_CQ_07092018.xlsx");
            Workbook wb = WorkbookFactory.create(inp);

            for(int i=0;i<wb.getNumberOfSheets();i++) {
                System.out.println(wb.getSheetAt(i).getSheetName());
                echoAsCSV(wb.getSheetAt(i));
            }
        } catch (InvalidFormatException ex) {
            Logger.getLogger(ExcelReading.class.getName()).log(Level.SEVERE, null, ex);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(ExcelReading.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(ExcelReading.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                inp.close();
            } catch (IOException ex) {
                Logger.getLogger(ExcelReading.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}

嗨,

我正在使用上面的代码将excel xlsx格式转换为csv(逗号分隔)格式。它将文件转换为csv格式,但是当我打开文件时,它显示以下错误

“'CH13XC009.csv'的文件格式和扩展名不匹配。该文件可能已损坏或不安全。除非您不信任其来源,否则请不要打开它。“

之后,我必须手动将其转换为csv格式。我做错了什么,但我不知道是什么?谁能帮我吗??

0 个答案:

没有答案