首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

在Java中将.csv转换为.xls

可以通过使用Apache POI库来实现。Apache POI是一个用于操作Microsoft Office格式文件的Java库,包括Excel、Word和PowerPoint等文件格式。

首先,你需要在Java项目中引入Apache POI的依赖。可以通过Maven或Gradle等构建工具来添加以下依赖:

代码语言:xml
复制
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>4.1.2</version>
</dependency>

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>4.1.2</version>
</dependency>

接下来,你可以使用以下代码将.csv文件转换为.xls文件:

代码语言:java
复制
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.*;

public class CSVtoXLSConverter {
    public static void main(String[] args) {
        String csvFilePath = "path/to/input.csv";
        String xlsFilePath = "path/to/output.xls";

        try {
            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("Sheet1");

            BufferedReader bufferedReader = new BufferedReader(new FileReader(csvFilePath));
            String line;
            int rowNumber = 0;

            while ((line = bufferedReader.readLine()) != null) {
                String[] data = line.split(",");
                Row row = sheet.createRow(rowNumber++);

                for (int i = 0; i < data.length; i++) {
                    Cell cell = row.createCell(i);
                    cell.setCellValue(data[i]);
                }
            }

            bufferedReader.close();

            FileOutputStream fileOutputStream = new FileOutputStream(xlsFilePath);
            workbook.write(fileOutputStream);
            workbook.close();
            fileOutputStream.close();

            System.out.println("Conversion completed successfully.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

以上代码将读取指定路径的.csv文件,并将其内容逐行写入新创建的.xls文件中。请确保在代码中将csvFilePathxlsFilePath替换为实际的文件路径。

这是一个基本的将.csv转换为.xls的示例。你可以根据实际需求进行修改和扩展。同时,腾讯云也提供了一系列与Excel相关的产品和服务,例如腾讯云对象存储 COS(https://cloud.tencent.com/product/cos)用于存储和管理文件,腾讯云函数计算 SCF(https://cloud.tencent.com/product/scf)用于处理文件转换等任务。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的沙龙

领券