[英]C# -export datagridview to excel with leading zero in c#
While exporting the datagridview to Excel in C#.net ,leading zeros are missing. 在C#.net中将datagridview导出到Excel时,缺少前导零。 For example : Data in the cell is "001693" After exporting to excel it is displaying me like this "1693".
例如:单元格中的数据为“001693”导出到excel后,它显示为“1693”。 Please help me out of this.
请帮我解决这个问题。 this is my code;
这是我的代码;
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;
worksheet = workbook.Sheets["Sheet1"];
worksheet = workbook.ActiveSheet;
worksheet.Name = "Exported from gridview";
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();
}
}
var saveFileDialoge = new SaveFileDialog();
saveFileDialoge.FileName = "output";
saveFileDialoge.DefaultExt = ".xlsx";
if (saveFileDialoge.ShowDialog() == DialogResult.OK)
{
workbook.SaveAs(saveFileDialoge.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);
app.Visible = true;
You need to set text format to cell where you want to save number with leading zeroes. 您需要将文本格式设置为要使用前导零保存数字的单元格。 In this sample I add code which set text format for entire row to speed up processing.
在此示例中,我添加了为整行设置文本格式的代码,以加快处理速度。
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
(worksheet.Rows[i+2 + ":" + i+2, System.Reflection.Missing.Value] as Excel.Range).NumberFormat = "@";
for (int j = 0; j < dataGridView1.Columns.Count; j++)
{
worksheet.Cells[i + 2, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.