【问题标题】:How to output a single file for each row of an excel file read in?如何为读入的excel文件的每一行输出一个文件?
【发布时间】:2015-06-16 17:08:56
【问题描述】:

如何为每行excel数据输出一个文件?现在它输出正确数量的文件,但数据行增加了,所以文件 1 是正确的,文件 2 有第 1 行和第 2 行,等等。

 Dim smNum As Integer = 0

        If rowct > 0 Then

            For rr As Integer = 10 To rowct
                For cc As Integer = 1 To colct
                    val = CType(r.Cells(rr, cc), Excel.Range).Value

                    If val = "" Then Exit For

                    str.Append(ht((cc - 1).ToString)).Append(",")
                    str.Append(val)

                    'assigning the sample managaer num in column 1
                    If cc = 1 Then
                        smNum = val
                        file_name = selectedFile.Substring(13, 16) & "_" & smNum & "_" & todays_date & file_count & ".csv"
                        full_path = save_file_path & file_name
                        MessageBox.Show("Sample Manager Number: " & val & full_path)
                    End If

                    If cc < colct Then
                        str.Append(",")
                    End If

                    My.Computer.FileSystem.WriteAllText(full_path, str.ToString, False)
                    lstFileOut.Items.Add(file_name)

                Next
                'str.AppendLine()
            Next

        End If

【问题讨论】:

  • For rr 循环内重新初始化你的字符串生成器,这样它就不会累积超过一行的数据
  • @Plutonix 我知道它会是这样的小东西,我已经看了太久了。非常感谢!!!
  • 您应该将WriteAllTextlstFileOut.Add 行移到列循环之外(str.AppendLine 被注释掉的位置)。这些也只需要每行运行一次。然后,您应该投票赞成@the_lotus 的答案,因为您注意到了这一点
  • @Plutonix 我确实将WriteAllTextlstFiteOut.Add 移到了列循环之外。这样做是有道理的。

标签: vb.net excel visual-studio-2010


【解决方案1】:

在每一行之前使用StringBuilder.Clear

        For rr As Integer = 10 To rowct
            str.Clear()

            For cc As Integer = 1 To colct

我还建议每行调用一次 My.Computer.FileSystem.WriteAllText,因为您要在每列上写入文件。

【讨论】:

  • 是的...作者如何不复制行数据给定的位置?
  • @Plutonix 第三个参数设置为 [append] false,每次写入都会覆盖整个文件。相当没用...但是 lstFileOut 将包含很多重复项。
  • @the_lotus 所以最后一行没有被写入文件,文件只是空白,知道为什么会这样吗?
  • @0723kas 你试过放断点吗?也许 rowct 差了一个
  • @the_lotus 我设置了一个断点并手动遍历整个文件,它正确输出了最后一个文件。我是 VB 编程新手,所以我不知道从哪里开始。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-10
  • 1970-01-01
相关资源
最近更新 更多