您的位置:首页 > 其它

如何把DataGridView中的数据导入Excel

2010-05-12 15:32 411 查看
现在很多客户都要求软件实现把DataGridView中的数据导入到Excel这项功能,现在网上很多方法都需要添加一些组件,但是本人感觉没有必要,而且编写的代码比较复杂,现在把一种简单的方法说出来,以飨读者!源代码如下:

//buttonToExcel是button的ID

private void buttonToExcel_Click(object sender, EventArgs e)
{

SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = true;

//Excel文件保存的路径初始化为D盘,根据需要可以做适当的修改
saveFileDialog.InitialDirectory = "D://";
saveFileDialog.CreatePrompt = true;
saveFileDialog.Title = "Export Excel File To";
saveFileDialog.ShowDialog();
Stream myStream;
myStream = saveFileDialog.OpenFile();
StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
string str = "";
try
{
//写标题
for (int i = 0; i < this.dataGridView1.ColumnCount; i++)
{
if (i > 0)
{
str += "/t";
}

str += this.dataGridView1.Columns[i].HeaderText;
}
sw.WriteLine(str);
//写内容
for (int j = 0; j < this.dataGridView1.Rows.Count; j++)
{
string tempStr = "";
for (int k = 0; k < this.dataGridView1.Columns.Count; k++)
{
if (k > 0)
{
tempStr += "/t";
}
tempStr += this.dataGridView1.Rows[j].Cells[k].Value + "";
}
sw.WriteLine(tempStr);
}

sw.Close();
myStream.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}

finally
{
sw.Close();
myStream.Close();
}
MessageBox.Show("导入Excel成功!");

}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: