How to format data extracted from datagridview to excel

Asked

Viewed 83 times

1

    private void button1_Click_1(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;
        worksheet = workbook.Sheets["Plan1"];
        worksheet = workbook.ActiveSheet;
        for (int i = 1; i < dGVPosicaoEstoque.Columns.Count + 1; i++)
        {
            worksheet.Cells[1, i] = dGVPosicaoEstoque.Columns[i - 1].HeaderText;
        }
        for (int i = 0; i < dGVPosicaoEstoque.Rows.Count - 1; i++)
        {
            for (int j = 0; j < dGVPosicaoEstoque.Columns.Count; j++)
            {
                if (dGVPosicaoEstoque.Rows[i].Cells[j].Value != null)
                {
                    worksheet.Cells[i + 2, j + 1] = dGVPosicaoEstoque.Rows[i].Cells[j].Value.ToString();
                }
                else
                {
                    worksheet.Cells[i + 2, j + 1] = "";
                }
            }
        }
    }

I need to format the data being extracted for excel because it is not differentiating (.)point from (,)comma. Example: The extracted value is in this way (109.390.759) and the correct one would be (109.390,759).

1 answer

1

From what I understand, you want to convert a list value dGVPhysical in the form 109.390,759.

Assuming this value is a double and is registered as 109390.759. In this case you can use the method String.Format (documentation here) to format it the way you want before inserting it into the spreadsheet.

Take an example:

double valor = 109390.759;

string valorFormatado = string.Format("{0:0,0.000}", valor);

Console.WriteLine(valorFormatado);    // valor impresso: 109.390,759

Browser other questions tagged

You are not signed in. Login or sign up in order to post.