Java循环遍历文件将csv转换为xls

标签 java excel csv

有谁知道如何使用下面的脚本循环遍历目录中的文件?我已经尝试过,但我不知道如何将变量分配给以下行:

CSVReader reader = new CSVReader(new FileReader(file));

它必须是一个弹出语法错误的字符串。

import java.io.*;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import au.com.bytecode.opencsv.CSVReader;

class Test {
    public static void main(String[] args) throws IOException {
        Workbook wb = new HSSFWorkbook();
        CreationHelper helper = wb.getCreationHelper();
        Sheet sheet = wb.createSheet("new sheet");

        CSVReader reader = new CSVReader(new FileReader("data.csv"));
        String[] line;
        int r = 0;
        while ((line = reader.readNext()) != null) {
            Row row = sheet.createRow((short) r++);

            for (int i = 0; i < line.length; i++)
                row.createCell(i)
                   .setCellValue(helper.createRichTextString(line[i]));
        }

        // Write the output to a file
        FileOutputStream fileOut = new FileOutputStream("workbook.xls");
        wb.write(fileOut);
        fileOut.close();
    }
}

最佳答案

您好,我不知道我是否正确理解您的问题。 但我建议尝试这样的事情: 您可以使用 Path 和 Files 类来循环访问目录。 然后您可以使用您的代码来编辑文件

import java.io.*;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import au.com.bytecode.opencsv.CSVReader;

class Test {

    public static void main(String[] args) throws IOException {
// here you enter the path to your directory.
// for example: Path workDir = Paths.get("c:\\workspace\\csv-files")

        Path workDir = Paths.get("path/to/dir");
// the if checks whether the directory truly exists
        if (!Files.notExists(workDir )) {
// this part stores all files withn the directory in a list
            try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(workDir )) {
                for (Path path : directoryStream) {
                    Workbook wb = new HSSFWorkbook();
                    CreationHelper helper = wb.getCreationHelper();
                    Sheet sheet = wb.createSheet("new sheet");
// here you insert the name of the file (stored in the Path object) into your method
                    CSVReader reader = new CSVReader(new FileReader(path.toString()));
                    String[] line;
                    int r = 0;
                    while ((line = reader.readNext()) != null) {
                        Row row = sheet.createRow((short) r++);

                        for (int i = 0; i < line.length; i++)
                            row.createCell(i)
                                    .setCellValue(helper.createRichTextString(line[i]));
                    }

                    // Write the output to a file
                    FileOutputStream fileOut = new FileOutputStream(path.getName().replaceAll("csv", "xls"));
                    wb.write(fileOut);
                    fileOut.close();
                }

            } catch (IOException e) {
                System.out.println(e.getMessage());
            } else {
                 System.out.println("directory " + workDir.toString() + " does not exist" )

        }

    }
}

关于Java循环遍历文件将csv转换为xls,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45761398/

相关文章:

c# - OleDb 连接不读取 excel 文件中的所有行

python - 在 Python 中对 gzipped 文件使用 csvreader

花括号之间的Java正则表达式匹配

excel - 将粘贴制表符分隔的结果复制到 excel 文件中

java treeset 抛出 illegalArgumentException : key out of range

excel - "Compile error: Automation error"VBE生成Worksheet_Change私有(private)子时

python - 从python中的CSV文件中删除特定行

csv - Pyarrow read_csv 如何处理不同的文件编码?

java - Selenium Web 驱动程序 : Extracted Chrome Browser logs are incomplete

java - 信任存储与 key 存储 - 使用 keytool 创建