private void button2_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Excel files (*.xls)|*.xls";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.CreatePrompt = true;
saveFileDialog.Title = "導出Excel文件到";
saveFileDialog.ShowDialog();
try
{
Stream myStream;
myStream = saveFileDialog.OpenFile();
StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding("utf-8"));
string str = "";
//寫標題
for (int i = 0; i < grid1.ColumnCount; i++)
{
if (i > 0)
{
str += "\t";
}
str += grid1.Columns[i].HeaderText;
}
sw.WriteLine(str);
//寫內容
for (int j = 0; j < grid1.Rows.Count; j++)
{
string tempStr = "";
for (int k = 0; k < grid1.Columns.Count; k++)
{
if (k > 0)
{
tempStr += "\t";
}
tempStr += grid1.Rows[j].Cells[k].Value.ToString();
}
sw.WriteLine(tempStr);
}
MessageBox.Show("導出成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
sw.Close();
myStream.Close();
}
catch (Exception)
{
//MessageBox.Show(ex.ToString());
}
finally
{
//sw.Close();
//myStream.Close();
}
}
如上 ColumnCount 、Rows、Columns等在 "System.Windows.From.DataGrid"不包含"
winforms是datagridview,asp.net才是datagrid