C#之四十三 从DataGridView导出数据到Excel

标签: datagridview数据gridviewexcel
308人阅读 评论(0) 收藏 举报
分类:

publicvoid outExcel(DataGridView gridView)
{
if (gridView.Rows.Count== 0)
{
MessageBox.Show("没有数据可供导出!","提示", MessageBoxButtons.OK,MessageBoxIcon.Information);
return;
}
else
{
 
SaveFileDialog saveFileDialog= new SaveFileDialog();
saveFileDialog.Filter= "Execl files (*.xls)|*.xls";
saveFileDialog.FilterIndex= 0;
saveFileDialog.RestoreDirectory= true;
saveFileDialog.CreatePrompt= true;
saveFileDialog.Title= "保存为Excel文件";
saveFileDialog.ShowDialog();
 
if (saveFileDialog.FileName.IndexOf(":")< 0) return; //被点了"取消"
 
Stream myStream;
myStream= saveFileDialog.OpenFile();
StreamWriter sw= new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
string columnTitle= "";
try
{
//写入列标题
for (inti = 0; i < this.dataGridView1.ColumnCount; i++)
{
if (i> 0)
{
columnTitle+= "\t";
}
columnTitle+= this.dataGridView1.Columns[i].HeaderText;
}
sw.WriteLine(columnTitle); 
//写入列内容
for (intj = 0; j
{
string columnValue= "";
for (intk = 0; k < this.dataGridView1.Columns.Count; k++)
{
if (k> 0)
{
columnValue+= "\t";
}
if (this.dataGridView1.Rows[j].Cells[k].Value== null)
columnValue+= "";
else
columnValue+= this.dataGridView1.Rows[j].Cells[k].Value.ToString().Trim();
}
sw.WriteLine(columnValue);
}
sw.Close();
myStream.Close();
}
catch (Exceptione)
{
MessageBox.Show(e.ToString());
}
finally
{
sw.Close();
myStream.Close();
}
}
}
 


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场