【发布时间】:2014-10-21 19:20:19
【问题描述】:
我正在将两个(1 列)DGV 和一个文本框的值写入文本文件。文本框值是标题,DGV1 是一列字符串(例如 SI CA S C...等),DGV2 是一列格式为 11.23 或 0.01 的数字。这些格式正是我希望它们在 DGV 中显示的方式,但是这种格式不会延续到这些值输出到的文本文件中。这是我希望文本文件的样子:
A012345 101 1.03
SI 32.13
C 1.45
CA 0.03
这就是我得到的:
A012345 101 1.03
SI32.13015
C1.452359
CA0.032568
代码如下:
Try
Dim da, da2 As OleDbDataAdapter
Dim ds, ds2 As DataSet
'open connection to nit2.xlsm'
Dim cn As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=""" & TextBox2.Text & """;Extended Properties=""Excel 12.0;HDR=YES;""")
'Fill dataviewgrid1 with element symbols, string, once'
da = New OleDbDataAdapter("select * from [Sheet1$A:A" & lastrow & "]", cn)
ds = New System.Data.DataSet
da.Fill(ds)
DataGridView1.DataSource = ds.Tables(0)
'''''''''''''loop through each sample and write to text file'''''''''''''''''''''''
da2 = New OleDbDataAdapter("select * from [Sheet1$B:B" & lastrow & "]", cn)
ds2 = New System.Data.DataSet
da2.Fill(ds2)
DataGridView2.DataSource = ds2.Tables(0)
'write sample heading to textbox1, looped'
TextBox1.Text = "Q0" & xlWsheet1.Cells(1, 2).Value & " " & xlWsheet2.Cells(1, 2).Value
'write to text file each data analysis point with formatted heading, looped'
Dim title As String = TextBox1.Text
Dim sub_title As String = title.Substring(0, 16)
Using writer As New System.IO.StreamWriter(fName, True)
writer.WriteLine(sub_title) 'heading'
Dim symbol, SymbolT As String
Dim compo As String
For cell1 As Integer = 0 To (DataGridView1.Rows.Count - 2)
symbol = Me.DataGridView1(0, cell1).Value 'element symbol'
symbolT = symbol.Trim
compo = Me.DataGridView2(0, cell1).Value 'composition'
writer.WriteLine(symbolT & compo)
Next
writer.Close()
End Using
cn.Close()
如何格式化 DGV2 中的数字,使其仅显示为 2 位小数?
我还需要设置 SI 和 32.13 之间的间距(例如),以便每行中的小数点对齐。
正在格式化...有人吗?
【问题讨论】:
-
顺便说一句,不要错过
For cell1 As Integer = 0 To (DataGridView1.Rows.Count - 2)的一行 - 似乎最后一行有点左(除非该行是空的,这是有道理的) -
是的,感谢 fsintegral。我想这是早期版本遗留下来的。好眼力!
标签: vb.net file text datagridview