繁体   English   中英

c#导出DataGridView内容

[英]c# export DataGridView content

我从 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", MessageBoxButtons.OK, 
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 += ",";
}

标准数字格式字符串……是 MS 文档,有很多使用String.Format方法的信息和示例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM