开发者

How to preserve formats when generating a CSV file from DataGridView?

开发者 https://www.devze.com 2023-02-19 08:51 出处:网络
I have the below code to generate a CSV file from DataGridView and working fine. But it is not preserving the exact formats. For example, I have 125600.00 in one cell and 08 in another cell in the Dat

I have the below code to generate a CSV file from DataGridView and working fine. But it is not preserving the exact formats. For example, I have 125600.00 in one cell and 08 in another cell in the DataGridView. When I opened the CSV file using Excel, it is showing them as 125600 and 8. And when I opened the CSV file using a notepad, it shows them correct 125600.00 and 08. Is there something that I can do to see the same formats in the excel? Thanks for any suggestions.

private void btnPrint_Click(object sender, EventArgs e)
    {
        sbM开发者_运维问答ainFile = new StringBuilder();
        int dgcolcount = this.dataGridView1.Columns.Count;

        for (int i = 0; i < dgcolcount; i++)
        {
            sbMainFile.Append(this.dataGridView1.Columns[i].Name);
            if (i < dgcolcount - 1)
            {
                sbMainFile.Append(",");
            }
        }
        sbMainFile.Append("\r\n");

        StringBuilder sbRow = null;

        foreach (DataGridViewRow row in this.dataGridView1.Rows)
        {
            sbRow = new StringBuilder();
            for (int i = 0; i < dataGridView1.Columns.Count; i++)
            {
                sbRow.Append(row.Cells[i].Value.ToString());
                if (i < dgcolcount - 1)
                {
                    sbRow.Append(",");
                }
            }
            sbMainFile.AppendLine(sbRow.ToString());
        }

        SaveFileDialog savefile = new SaveFileDialog();
        savefile.FileName = "default";
        savefile.Filter = "CSV Files | *.csv";
        savefile.DefaultExt = "csv";

        if (savefile.ShowDialog() == DialogResult.OK)
        {
            using (System.IO.StreamWriter sw = new System.IO.StreamWriter(savefile.FileName))
                sw.Write(sbMainFile.ToString());
        }

    }


You could save the "column values" as a string; e.g. 08 as ="08"

change

sbRow.Append(row.Cells[i].Value.ToString());

to

sbRow.AppendFormat("=\"{0}\"", row.Cells[i].Value.ToString());


There is nothing wrong with your code. That is actually a problem with Excel formatting your data for you. You don't actually lose any data. You simply have to specify the format in Excel. (If you click on one of your cells where the format is mangled you can actually see the "raw" value in the f(x) editor.)

0

精彩评论

暂无评论...
验证码 换一张
取 消