如何解决C#导出DataGridView内容
我从datagridview中导出了一些虚拟数据。 “ 1.000”
private void btnSaveCalibTable_Click(object sender,EventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
if (sfd.ShowDialog() == DialogResult.OK)
{
System.IO.StreamWriter file = new
System.IO.StreamWriter(@"C:\Users\Desktop\\sample.txt");
try
{
string sLine = "";
for(int i=0; i<dgvSensorCalibTable.Rows.Count-1; i++)
{
for(int j=0; j < dgvSensorCalibTable.Columns.Count; j++)
{
sLine += dgvSensorCalibTable.Rows[i].Cells[j].Value + ",";
}
sLine += "\n";
}
file.WriteLine(sLine);
file.Close();
System.Windows.Forms.MessageBox.Show("Export Complete.","Program Info",MessageBoxButtons.OK,MessageBoxIcon.Information);
}
catch (System.Exception err)
{
System.Windows.Forms.MessageBox.Show(err.Message,"Error",MessageBoxIcon.Error);
file.Close();
}
}
}
当我将其导出到.txt文件时,我得到了: 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,
我的问题是如何将其导出到数据表1.000中而不是1中?
解决方法
获取正确格式的数字将取决于基础单元格数据类型。
要格式化数字,请使用String.Format(..)
方法。但是,如果单元格数据类型为string
,则可能需要将字符串转换为decimal
。
例如,如果单元格为decimal
类型的单元格,则可以使用…
sLine += String.Format("{0:0.000}",(decimal)dgvSensorCalibTable.Rows[i].Cells[j].Value);
同样,这假设基础数据是decimal
类型。
此外,为避免在结尾加上多余的逗号(,)...
string formattedLine = String.Format("{0:0.000}",(decimal)dgvSensorCalibTable.Rows[i].Cells[j].Value);
sLine += formattedLine;
if (j < dgvSensorCalibTable.Columns.Count - 1) {
sLine += ",";
}
Standard numeric format strings…是MS文档,并使用String.Format
方法提供了很多信息和示例。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。