java - 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();
}
}
解决方案
您可以在 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
推荐阅读
- ansible - 在复杂列表变量中使用模板
- visual-studio-code - 如何在VSCode集成终端Ctrl+Shift+←/→选择上一个或下一个单词?
- python - 如何在 Python 中获取 dBA 噪声级别?
- angular - 如何设置Angular 8轮事件的灵敏度?
- python - Python 根据其他列表求和列表元素
- javascript - 通过计时器重置文本框文本并再次关注它,在javascript中
- java - 用右移编码整数
- c++ - 在 C++ 中按下左键和释放左键时如何获取鼠标光标坐标?
- .htaccess - CakePHP 3 htaccess 忽略目录
- android - 以编程方式设置 AppBarLayout 子项的 minHeight