我正在使用C# windows forms application
,使用DataGridView
将数据从Interop Open Library 15.0
导出到Excel。我在DataGridView中的数据是这样的,它包含很少的列,其浮点类型数据四舍五入到三个小数点。
例如,我的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 / Day和Avg Price导出上述数据,无论价值是多少,都有三个小数点。
有解决此问题的好方法吗?
答案 0 :(得分:2)
10.000
是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.
但是我会做出另一个改变:
将数据放入数组并在一次调用中设置值(并设置范围的格式):
int[,] data = new int[rows,cols];
... loop
data[i,j] = value;
var range = indexworksheet.get_Range(...);
range.Value = data;
range.NumberFormat = "#,##0.000";
答案 1 :(得分:0)
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);
}
}
尝试使用此格式化字符串。