Gridview export to excel - Formatting problems

无人久伴 提交于 2020-01-16 18:40:31

问题


I am not sure about what is going on here. I use this button event to export data from datagridview to excel and the data get exported, file saved, etc.., so it looks like is working fine to me.

private void button2_Click(object sender, EventArgs e)
    {
        Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
        Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
        Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
        app.Visible = true;
        try
        {
            worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Sheets["Sheet1"];
            worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.ActiveSheet;
            worksheet.Name = "Gioietta Environment Data";
            for (int i = 1; i < dataGridView1.Columns.Count + 1; i++)
            {
                worksheet.Cells[1, i] = dataGridView1.Columns[i - 1].HeaderText;
            }
            for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
            {
                for (int j = 0; j < dataGridView1.Columns.Count; j++)
                {
                    worksheet.Cells[i + 2, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();
                }
            }
            string fileName = String.Empty;
            SaveFileDialog saveFileDialog1 = new SaveFileDialog();
            saveFileDialog1.Filter = "Excel files |*.xls|All files (*.*)|*.*";
            saveFileDialog1.FilterIndex = 2;
            saveFileDialog1.RestoreDirectory = true;

            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                fileName = saveFileDialog1.FileName;
                workbook.SaveAs(fileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            }
            else
                return;               
        }
        catch (System.Exception ex)
        {

        }
        finally
        {
            app.Quit();
            workbook = null;
            app = null;
        }
    }

The problem I am experiencing is on that the excel side. Basically even formatting the exported values as numbers, I cannot use them. I cannot even sum them up! If I re-type the value in the same cell manually than it become usable. Has this something to to with the exporting process?

This is how I load the data to the datagridview:

var time = DateTime.Now.ToString("HH:mm:ss");
        dataGridView1.Rows.Add(new string[] { time, textBox1.Text, textBox2.Text });


回答1:


The problem comes from this line and how DataGridView is populated:

worksheet.Cells[i   2, j   1] = dataGridView1.Rows[i].Cells[j].Value.ToString();

Data are exported as string whatever the type due to .ToString() and they are string anyway.

As DataGridViewCell.Value contains a string, so you have to cast the dgvCell.Value to a numeric value before exporting. For example:

if (j == 1 || j == 2) 
{
    worksheet.Cells(i   2, j   1) = Convert.ToDecimal(dataGridView1.Rows(i).Cells(j).Value)
} 
else 
{
    worksheet.Cells[i   2, j   1] = dataGridView1.Rows[i].Cells[j].Value.ToString();
}

If DataGridViewCell.Value contains a numeric value (Decimal, Double, Integer, ...), Just remove .toString() and it should work as expected (Excel will set the appropriate type).

In both cases, if you want to apply a custom format for displaying in Excel, you will loose it during export, and you will have to explictly set it in Excel, using Range.NumberFormat Property. These Q/A can help to achieve this:

  • microsoft.interop.excel Formatting cells

  • excel interop : NumberFormat #,##0.000 doesn't display the expected result



来源:https://stackoverflow.com/questions/17251162/gridview-export-to-excel-formatting-problems

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!