使用java更新特定单元格的csv文件

发布于 2024-10-06 15:47:44 字数 104 浏览 1 评论 0原文

嗨,我有一个小问题,我认为我只是在一行代码上没有得到正确的语法。基本上,我可以写入 csv 文件并使用字符串标记器查找特定记录,但它不会更新/编辑该记录的指定单元格。记录保持不变。请帮忙....

Hi i have a small problem and think i'm just not getting the correct syntax on one line of code. basically, i can write into my csv file and find a specific record using string tokenizer but it is not updating/editing the specified cells of that record. the record remains the same. please help....

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

手长情犹 2024-10-13 15:47:44

我在java中使用了 http://opencsv.sourceforge.net

嗨,
这是通过指定行和列更新 CSV 的代码

/**
 * Update CSV by row and column
 * 
 * @param fileToUpdate CSV file path to update e.g. D:\\chetan\\test.csv
 * @param replace Replacement for your cell value
 * @param row Row for which need to update 
 * @param col Column for which you need to update
 * @throws IOException
 */
public static void updateCSV(String fileToUpdate, String replace,
    int row, int col) throws IOException {

File inputFile = new File(fileToUpdate);

// Read existing file 
CSVReader reader = new CSVReader(new FileReader(inputFile), ',');
List<String[]> csvBody = reader.readAll();
// get CSV row column  and replace with by using row and column
csvBody.get(row)[col] = replace;
reader.close();

// Write to CSV file which is open
CSVWriter writer = new CSVWriter(new FileWriter(inputFile), ',');
writer.writeAll(csvBody);
writer.flush();
writer.close();
}

这个解决方案对我有用,
干杯!

I have used http://opencsv.sourceforge.net in java

Hi,
This is the code to update CSV by specifying row and column

/**
 * Update CSV by row and column
 * 
 * @param fileToUpdate CSV file path to update e.g. D:\\chetan\\test.csv
 * @param replace Replacement for your cell value
 * @param row Row for which need to update 
 * @param col Column for which you need to update
 * @throws IOException
 */
public static void updateCSV(String fileToUpdate, String replace,
    int row, int col) throws IOException {

File inputFile = new File(fileToUpdate);

// Read existing file 
CSVReader reader = new CSVReader(new FileReader(inputFile), ',');
List<String[]> csvBody = reader.readAll();
// get CSV row column  and replace with by using row and column
csvBody.get(row)[col] = replace;
reader.close();

// Write to CSV file which is open
CSVWriter writer = new CSVWriter(new FileWriter(inputFile), ',');
writer.writeAll(csvBody);
writer.flush();
writer.close();
}

This solution worked for me,
Cheers!

薄情伤 2024-10-13 15:47:44

我使用下面的代码,将一个字符串替换为另一个字符串,它的工作方式完全符合我需要的方式:

public static void updateCSV(String fileToUpdate) throws IOException {
        File inputFile = new File(fileToUpdate);

        // Read existing file
        CSVReader reader = new CSVReader(new FileReader(inputFile), ',');
        List<String[]> csvBody = reader.readAll();
        // get CSV row column and replace with by using row and column
        for(int i=0; i<csvBody.size(); i++){
            String[] strArray = csvBody.get(i);
            for(int j=0; j<strArray.length; j++){
                if(strArray[j].equalsIgnoreCase("Update_date")){ //String to be replaced
                    csvBody.get(i)[j] = "Updated_date"; //Target replacement
                }
            }
        }
        reader.close();

        // Write to CSV file which is open
        CSVWriter writer = new CSVWriter(new FileWriter(inputFile), ',');
        writer.writeAll(csvBody);
        writer.flush();
        writer.close();
    }

I used the below code where I will replace a string with another and it worked exactly the way I needed:

public static void updateCSV(String fileToUpdate) throws IOException {
        File inputFile = new File(fileToUpdate);

        // Read existing file
        CSVReader reader = new CSVReader(new FileReader(inputFile), ',');
        List<String[]> csvBody = reader.readAll();
        // get CSV row column and replace with by using row and column
        for(int i=0; i<csvBody.size(); i++){
            String[] strArray = csvBody.get(i);
            for(int j=0; j<strArray.length; j++){
                if(strArray[j].equalsIgnoreCase("Update_date")){ //String to be replaced
                    csvBody.get(i)[j] = "Updated_date"; //Target replacement
                }
            }
        }
        reader.close();

        // Write to CSV file which is open
        CSVWriter writer = new CSVWriter(new FileWriter(inputFile), ',');
        writer.writeAll(csvBody);
        writer.flush();
        writer.close();
    }
未央 2024-10-13 15:47:44

您正在做这样的事情:

  String line = readLineFromFile();
  line.replace(...);

这不是编辑文件,而是从文件中的一行创建一个新字符串

String 实例是不可变的,因此您进行的 replace 调用会返回一个字符串,它不会修改原始字符串。

使用允许您读取和写入文件的文件流 - 即 RandomAccessFile 或(更简单地)写入新文件,然后用新文件替换旧文件

在伪代码中:

for (String line : inputFile) {
    String [] processedLine = processLine(line);
    outputFile.writeLine(join(processedLine, ","));
}

private String[] processLine(String line) {
    String [] cells = line.split(","); // note this is not sufficient for correct csv parsing.
    for (int i = 0; i < cells.length; i++) {
        if (wantToEditCell(cells[i])) {
           cells[i] = "new cell value";
        }
    }

    return cells;
}

另外,请看一下 这个问题。有一些库可以帮助您处理 csv。

You're doing something like this:

  String line = readLineFromFile();
  line.replace(...);

This is not editing the file, it's creating a new string from a line in the file.

String instances are immutable, so the replace call you're making returns a new string it does not modify the original string.

Either use a file stream that allows you to both read and write to the file - i.e. RandomAccessFile or (more simply) write to a new file then replace the old file with the new one

In psuedo code:

for (String line : inputFile) {
    String [] processedLine = processLine(line);
    outputFile.writeLine(join(processedLine, ","));
}

private String[] processLine(String line) {
    String [] cells = line.split(","); // note this is not sufficient for correct csv parsing.
    for (int i = 0; i < cells.length; i++) {
        if (wantToEditCell(cells[i])) {
           cells[i] = "new cell value";
        }
    }

    return cells;
}

Also, please take a look at this question. There are libraries to help you deal with csv.

时光病人 2024-10-13 15:47:44

CSV 文件只是一个文件。如果您正在阅读它,它不会被更改。
因此,写下您的更改!

你有3种方法。

1

  1. 逐行阅读找到要更改的单元格。
  2. 如果需要,更改单元格并合成当前行的新版本。
  3. 将该行写入第二个文件。
  4. 完成后,您将获得源文件和结果文件。现在,如果您愿意,可以删除源文件并将结果文件重命名为 source.txt。

2

使用RandomAccess 文件写入文件的特定位置。

3

使用 CSV 解析器的可用实现之一(例如 http://commons.apache.org/sandbox/ csv/)
它已经支持您所需要的并公开了高级 API。

CSV file is just a file. It is not being changed if you are reading it.
So, write your changes!

You have 3 ways.

1

  1. read line by line finding the cell you want to change.
  2. change the cell if needed and composite new version of current line.
  3. write the line into second file.
  4. when you finished you have the source file and the result file. Now if you want you can remove the source file and rename the result file to source.

2

Use RandomAccess file to write into specific place of the file.

3

Use one of available implementations of CSV parser (e.g. http://commons.apache.org/sandbox/csv/)
It already supports what you need and exposes high level API.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文