Datagridview から Excel にデータを抽出する C# で記述されたアプリケーションがあります。私の問題は、Excel にエクスポートするときに 010498 のような数字が 10498 になり、先頭にゼロ (0) がない場合です。ゼロ (0) であってほしい。アプリケーション内または Excel 経由で C# でコードを記述して、解決策はありますか?
下手な英語で申し訳ありません。
最初の写真では datagridview のように見え、2 番目の写真ではエクスポート後にどのように 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;
}
}
}