将datagirdview中的数据导出到保留小数的Excel工作表中

我正在使用Interop Open Library 15.0从一个DataGridView导出数据到excel的C# windows forms application 。 我在DataGridView中的数据是这样的,它包含几个浮点types数据四舍五入到三个小数点的列。

例如,我在我的DataGridView中有一个数字10.000,但是当我将它导出到Excel时,它只输出10而不是10.000。

我正在使用下面的代码导出数据

 Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application(); // creating new WorkBook within Excel application Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing); // creating new Excelsheet in workbook Microsoft.Office.Interop.Excel._Worksheet indexWorkSheet = null; indexWorkSheet = workbook.Sheets[1]; // changing the name of active sheet indexWorkSheet.Name = "Index Summary"; indexWorkSheet.get_Range("A1").Style.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter; indexWorkSheet.get_Range("A10", "A30").Style.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter; string filelocation; SaveFileDialog SaveFile = new SaveFileDialog(); if (SaveFile.ShowDialog() == DialogResult.OK) { filelocation = SaveFile.FileName; for (int i = 1; i < dataGridViewIndex.Columns.Count + 1; i++) { indexWorkSheet.Cells[9, i + 3] = dataGridViewIndex.Columns[i - 1].HeaderCell.Value; } for (int i = 1; i < dataGridViewIndex.Rows.Count + 1; i++) { indexWorkSheet.Cells[i + 9, 3] = dataGridViewIndex.Rows[i - 1].HeaderCell.Value; } for (int i = 0; i < dataGridViewIndex.Rows.Count; i++) { for (int j = 0; j < dataGridViewIndex.Columns.Count; j++) { indexWorkSheet.Cells[i + 10, j + 4] = dataGridViewIndex.Rows[i].Cells[j].Value.ToString(); } } workbook.SaveAs(filelocation, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing); } 

我的DataGridView是在下面的屏幕截图 在这里输入图像说明

我想以BBL /天和平均价格输出以上数据,无论数值是多less,都有三位小数。

有没有解决这个问题的好方法?

10.000 IS 10 。 Excel默认使用“常规”格式,不会显示任何尾随零。 如果你想在excel格式化数字,你必须明确地做到这一点。

 indexWorkSheet.Cells[i + 10, j + 4] = dataGridViewIndex.Rows[i].Cells[j].Value.ToString(); indexWorkSheet.Cells[i + 10, j + 4].NumberFormat = "#,##0.000"; // or whatever format is appropriate. 

但是我会做另一个改变:

  • 使用范围而不是单元格 。 每个单元访问都是一个COM调用,这会增加过程的开销。 如果你运行一个体面的configuration文件反对它,我愿意打赌,绝大多数的时间都花在了手机上。

把你的数据放在一个数组中,并在一次调用中设置值(并设置范围的格式):

 int[,] data = new int[rows,cols]; ... loop data[i,j] = value; var range = indexworksheet.get_Range(...); range.Value = data; range.NumberFormat = "#,##0.000"; 
  for (int i = 0; i < dataGridViewIndex.Rows.Count; i++) { for (int j = 0; j < dataGridViewIndex.Columns.Count; j++) { int digitcount = 4; indexWorkSheet.Cells[i + 10, j + 4] = dataGridViewIndex.Rows[i].Cells[j].Value.ToString("F"+digitcount); } } 

试试这个来格式化string。