Winform中怎么将datagridview中数据导入到excel表中?
Winform中怎么将datagridview中数据导入到excel表中,在网上看了一下,都不能实现。
public static bool ExportDataGridViewToExcel1(DataGridView dataGridview1)
{
if (dataGridview1.Rows.Count <= 0)
{
MessageBox.Show("没有可导出的记录。", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
return false;
}
//设置保存对话框
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.CreatePrompt = true;
saveFileDialog.Title = "导出Excel文件到";
//
//打开保存对话框并判断,若在保存对话框上按取消按钮则返回false
if (saveFileDialog.ShowDialog() == DialogResult.Cancel)
{ return false; }
//
//把dataGridview1的内容写入要保存到的excle文档
Stream myStream;
myStream = saveFileDialog.OpenFile();
StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding("GBK"));
string str = "";
try
{
//写标题
for (int i = 0; i < dataGridview1.ColumnCount; i++)
{
if (i > 0)
{
str += "\t";
}
str += dataGridview1.Columns[i].HeaderText;
}
sw.WriteLine(str);
//写内容
for (int j = 0; j < dataGridview1.Rows.Count; j++)
{
string tempStr = "";
for (int k = 0; k < dataGridview1.Columns.Count; k++)
{
if (k > 0)
{
tempStr += "\t";
}
if (dataGridview1.Rows[j].Cells[k].Value != null)
tempStr += dataGridview1.Rows[j].Cells[k].Value.ToString();
}
sw.WriteLine(tempStr);
}
sw.Close();
myStream.Close();
return true;
}
catch (Exception e)
{
//显示错误信息
MessageBox.Show(e.ToString());
return false;
}
finally
{
sw.Close();
myStream.Close();
}
}