1

当我扫描 csv 文件时,我得到了奇怪的输出,将其拆分为 "," ,对于每一行的长度,我将 i + ":" 的第 i 个元素附加到 printwriter。我的原始输入看起来像这样。

8.035156 7.619141 7.105469

7.234375 7.8125 8.244141

6.615234 8.224609 6.361328

它们确实由“,”分隔。

输出应该是这样的

1:8.035156,2:7.619141,3:7.105469,4:7.072266

再次,它应该用“,”分隔。

但是输出看起来像这样,当我点击它给我时间的选择时甚至更奇怪。

01:08.0 02:07.6 03:07.1 04:07.1 05:07.4 06:07.2 07:07.6 08:07.1 09:07.1 10:07.2 
12:04:06 AM

只有当我,在 append 语句的末尾添加字符时,才会出现错误的输出。

public class GeneCsv
{
    public static void main(String[] args) throws IOException
    {
        File file = new File("file.csv");
        FileWriter writer = new FileWriter("/Users/home/fileExpression.csv");
        PrintWriter pw = new PrintWriter(writer);
        Scanner in = new Scanner(file);
        boolean firstLine = true;
        String[] temp = null;
        while (in.hasNextLine())
        {
            if (firstLine == true)
            {
                pw.println(in.nextLine());
                firstLine = false;
                continue;
            }
            else
            {
                String line = in.nextLine();
                temp = line.split(",");
                for (int i = 0; i < temp.length; i++)
                {
                    pw.append(i + ":" + temp[i] + ",");
                }
                pw.append("\n");
            }
        }

        pw.flush();
        pw.close();
        writer.close();
    }
}
4

1 回答 1

0

您的代码没有任何问题。问题是 Excel 将您的输出解释为一系列时间值。因此,第一列中的值1:8.035156被读取为 1 分钟 8.035156 秒。如果您查看实际的数据输出,您会发现它与所需的格式相匹配。

要让 Excel 将值视为文本,您需要将它们格式化为

="1:8.035156",="2:7.619141",="3:7.105469",="4:7.072266",

在 CSV 文件中。前导=和周围的引号可以解决问题。

另请参阅阻止 Excel 自动将某些文本值转换为日期

于 2012-05-23T04:02:54.603 回答