首页 > 解决方案 > Java 将 CSV 转换为 XLSX

问题描述

我正在尝试创建一个使用 Apache POI 将 .csv 文件转换为 .xlsx 文件的程序。除了生成的 .xlsx 文件没有正确显示带有变音符号(ü,ä,ö) 的德语字母外,一切正常。它只是打印一个问号。有人会这么好心来帮助我吗?任何帮助深表感谢。

这是我编写的代码。我不是 Java 专家,所以如果我的代码看起来很基础,我提前道歉。

private static void csvtoxlsx() {
    try{
        String csvfile = "test.csv";
        String xlsxfile = "test-changed.xlsx";
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet("sheet1");
        XSSFFont xssfFont = workbook.createFont();
        xssfFont.setCharSet(XSSFFont.ANSI_CHARSET);
        XSSFCellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setFont(xssfFont);
        String currentLine;
        int RowNum = 0;
        BufferedReader br = new BufferedReader(new FileReader(csvfile));
        while((currentLine = br.readLine()) != null){
            String[] str = currentLine.split(";");
            RowNum++;
            XSSFRow currentRow = sheet.createRow(RowNum);
            for(int i=0; i< str.length; i++){
                str[i] = str[i].replaceAll("\"","");
                str[i] = str[i].replaceAll("=","");
                XSSFCell cell = currentRow.createCell(i);
                cell.setCellStyle(cellStyle);
                cell.setCellValue(str[i].trim());
            }
        }
        FileOutputStream fileOutputStream = new FileOutputStream(xlsxfile);
        workbook.write(fileOutputStream);
        fileOutputStream.close();

        System.out.println("success");
    }catch (Exception e){
        e.printStackTrace();
    }
}

标签: java

解决方案


您可以在 BufferedReader 中传递如下所示的编码器,这样就可以按照您的预期正确读取字符。

        FileReader fileReader = new FileReader(file);
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("test.csv"), "windows-1252")); // Or try "Cp1252" in place of "windows-1252"

        String lineOfText;
        while ((lineOfText = br.readLine()) != null) {
            //do something
        }
        br.close();

参考:https ://docs.oracle.com/javase/7/docs/technotes/guides/intl/encoding.doc.html


推荐阅读