我有一个用 C# 编写的应用程序,它从 Datagridview 中提取数据到 excel。我的问题是当我导出到 excel 时有一个像 010498 这样的数字变成 10498,而开头没有零 (0)。我希望有零(0)。是否有任何可能的解决方案,无论是在应用程序中用 C# 编写代码还是通过 excel 编写代码?
感谢和抱歉英语不好。
在第一张图片中似乎是 datagridview 和在第二张图片中导出到 excel 后如何。在单元格 A3、F3、F4 的开头缺少零 (0)。任何解决方案我该如何解决?谢谢。
导出到 Excel 的代码。
private void excel_toolstripmenuitem_Click(object sender, EventArgs e)
{
Microsoft.Office.Interop.Excel.Application excelApp = null;
try
{
// instantiating the excel application class
object misValue = System.Reflection.Missing.Value;
excelApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook currentWorkbook = excelApp.Workbooks.Add(Type.Missing);
Microsoft.Office.Interop.Excel.Worksheet currentWorksheet = (Microsoft.Office.Interop.Excel.Worksheet)currentWorkbook.ActiveSheet;
currentWorksheet.Columns.ColumnWidth = 18;
if (dg1.Rows.Count > 0)
{
currentWorksheet.Cells[1, 1] = DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToShortTimeString();
int i = 1;
foreach (DataGridViewColumn dgviewColumn in dg1.Columns)
{
// Excel work sheet indexing starts with 1
currentWorksheet.Cells[2, i] = dgviewColumn.Name;
++i;
}
Microsoft.Office.Interop.Excel.Range headerColumnRange = currentWorksheet.get_Range("A2", "AY2");
headerColumnRange.Font.Bold = true;
headerColumnRange.Font.Color = 0xFF0000;
int rowIndex = 0;
for (rowIndex = 0; rowIndex < dg1.Rows.Count; rowIndex++)
{
DataGridViewRow dgRow = dg1.Rows[rowIndex];
for (int cellIndex = 0; cellIndex < dgRow.Cells.Count; cellIndex++)
{
currentWorksheet.Cells[rowIndex + 3, cellIndex + 1] = dgRow.Cells[cellIndex].Value;
}
}
Microsoft.Office.Interop.Excel.Range fullTextRange = currentWorksheet.get_Range("A1", "AY" + (rowIndex + 1).ToString());
fullTextRange.WrapText = true;
fullTextRange.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft;
}
using (SaveFileDialog exportSaveFileDialog = new SaveFileDialog())
{
exportSaveFileDialog.Title = "Save as";
exportSaveFileDialog.Filter = "Microsoft Office Excel Workbook(*.xls)|*.xls";
if (DialogResult.OK == exportSaveFileDialog.ShowDialog())
{
string fullFileName = exportSaveFileDialog.FileName;
currentWorkbook.SaveAs(fullFileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, System.Reflection.Missing.Value, misValue, false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Microsoft.Office.Interop.Excel.XlSaveConflictResolution.xlUserResolution, true, misValue, misValue, misValue);
currentWorkbook.Saved = true;
MessageBox.Show("The export was successful", "Export to Excel", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
if (excelApp != null)
{
excelApp.Quit();
excelApp = null;
}
}
}