spring - 使用 Apache poi 将 csv 转换为 xls/xlsx?

标签 spring spring-mvc apache-poi xssf poi-hssf

我需要在我的项目中将 csv 转换为 xls/xlsx 吗?我怎样才能做到这一点?任何人都可以给我发一些例子吗?我想用 Apache poi 来做。我还需要从 java 端创建一个单元格。

最佳答案

您可以尝试以下方法使用 apache-poi 创建 xlsx 文件。

public static void csvToXLSX() {
    try {
        String csvFileAddress = "test.csv"; //csv file address
        String xlsxFileAddress = "test.xlsx"; //xlsx file address
        XSSFWorkbook workBook = new XSSFWorkbook();
        XSSFSheet sheet = workBook.createSheet("sheet1");
        String currentLine=null;
        int RowNum=0;
        BufferedReader br = new BufferedReader(new FileReader(csvFileAddress));
        while ((currentLine = br.readLine()) != null) {
            String str[] = currentLine.split(",");
            RowNum++;
            XSSFRow currentRow=sheet.createRow(RowNum);
            for(int i=0;i<str.length;i++){
                currentRow.createCell(i).setCellValue(str[i]);
            }
        }

        FileOutputStream fileOutputStream =  new FileOutputStream(xlsxFileAddress);
        workBook.write(fileOutputStream);
        fileOutputStream.close();
        System.out.println("Done");
    } catch (Exception ex) {
        System.out.println(ex.getMessage()+"Exception in try");
    }
}

关于spring - 使用 Apache poi 将 csv 转换为 xls/xlsx?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18077264/

相关文章:

java - 将扩展名为 .xls 但另存为 xml 电子表格 2003 的文件转换为 .xls 文件格式

apache-poi - 如何使用 apache poi 以 mm/dd/yyyy 等 Excel 工作表日期格式打印确切的日期单元格值

java - 无法使用 Apache POI 为一行的某些部分添加项目符号点和样式(例如粗体和斜体)

Spring集成-文件:inbound-channel-adapter - remove original file

java - 如何运行OpenEHR gen框架?

java - com.querydsl.core.Tuple 的 ClassCastException

spring-mvc - 当客户端发送 Accept : */* 时,文本/html 优先于其他内容类型

hibernate - 由 : java. lang.NoClassDefFoundError: org/hibernate/cfg/Configuration 引起

java - 即使在加载图像时,Spring Boot 应用程序也会为资源中的所有静态内容返回 401

java - @ComponentScan 和 @Bean 在上下文配置中有什么区别?