Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create CSV file using java

Tags:

java

csv

I am going to create CSV files by using java. Here is a part of the code:

try{

    FileWriter writer = new FileWriter(sFileName);

    writer.append("Title");
    for(StoredArticle sa3:historyFile.keySet()){
        for(String k3:sa3.getTimeAndPopularity().keySet()){
            writer.append(',');
            writer.append(k3);
        }
    }
    writer.append('\n');

The problem is I am successfully create the CSV file. And in the for loop k3 is the time presented as format 2013/07/22 15:40:23. But the seconds "23" cannot be shown. The others are showing good. what's the problem please help.

This is the code of my entire class

package uk.ac.ncl.fanyaoxia.createCSV;

import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import uk.ac.ncl.fanyaoxia.monitor.MonitorRecentUpdates;
import uk.ac.ncl.fanyaoxia.monitor.StoredArticle;
import uk.ac.ncl.fanyaoxia.webpagefetch.ReadXml;

public class CreateCSVFile {
    private static Map < StoredArticle, ReadXml > historyFile;

    public CreateCSVFile() {
        historyFile = new HashMap < StoredArticle, ReadXml > ();
    }
    public void createFile() {
        generateCsvFile("HistoryTable.csv");
    }

    private static void generateCsvFile(String sFileName) {
        MonitorRecentUpdates csvFile = new MonitorRecentUpdates();
        historyFile = csvFile.getMap();
        try {

            FileWriter writer = new FileWriter(sFileName);

            writer.append("Title");
            for (StoredArticle sa3: historyFile.keySet()) {
                for (String k3: sa3.getTimeAndPopularity().keySet()) {
                    writer.append(',');
                    writer.append(k3);
                }
            }
            writer.append('\n');

            for (StoredArticle sa3: historyFile.keySet()) {
                writer.append(sa3.getStoredTitle());
                for (String k3: sa3.getTimeAndPopularity().keySet()) {
                    writer.append(',');
                    writer.append(sa3.getTimeAndPopularity().get(k3).toString());
                }
                writer.append('\n');
            }
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
like image 649
wadefanyaoxia Avatar asked Oct 22 '22 04:10

wadefanyaoxia


1 Answers

The seconds are being output as expected by the code. They are visible in a text editor.

They just weren't visible in the spreadsheet application MS Excel. One possible cause would be that the column width was too small.

[This answer summarizes the result of the conversation between the OP and myself above.]

like image 123
Andy Thomas Avatar answered Oct 28 '22 23:10

Andy Thomas