我不知道什麼是怎麼回事。我用這個按鈕事件將數據從DataGridView導出到Excel和數據取得匯出,文件保存,等,所以看起來是工作的罰款給我。的GridView導出到Excel - 格式化問題
private void button2_Click(object sender, EventArgs e)
{
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;
app.Visible = true;
try
{
worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Sheets["Sheet1"];
worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.ActiveSheet;
worksheet.Name = "Gioietta Environment Data";
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();
}
}
string fileName = String.Empty;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "Excel files |*.xls|All files (*.*)|*.*";
saveFileDialog1.FilterIndex = 2;
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
fileName = saveFileDialog1.FileName;
workbook.SaveAs(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);
}
else
return;
}
catch (System.Exception ex)
{
}
finally
{
app.Quit();
workbook = null;
app = null;
}
}
我遇到的問題在於excel方面。基本上甚至將導出的值格式化爲數字,我不能使用它們。我甚至不能總結它們!如果我手動重新鍵入同一個單元格中的值,它會變得可用。這件事與出口過程有關嗎?
這是我如何將數據加載到DataGridView:
var time = DateTime.Now.ToString("HH:mm:ss");
dataGridView1.Rows.Add(new string[] { time, textBox1.Text, textBox2.Text });
謝謝,但我已經試過了,問題persist.Still相同。 – FeliceM
@FeliceM按照數字類型從DataGridView價值? (小數,雙精度,整數,...)。如果沒有,則必須將其從字符串轉換爲數字類型。例如Ctype(cell.value,Decimal)。請注意,您將失去格式,並且必須在Excel中重新使用它。 – Chris
實際上是3個字符串。我可以將它們中的兩個轉換爲int,但後來變成了混亂,因爲第一個是字符串時間。 – FeliceM