将系统中的数据导入至excel表格中是非常常见的功能,特此记录一下,慢慢成长。。。。。。
方法一:
此方法有点问题,在保存时报错:Ox800A03EC,查资料无果,有知道解决办法的小伙伴请麻烦告知一下~~
代码如下:
public void ToExcel(DataGridView dataGridView1)
{
try
{
//没有数据的话就不往下执行
if (dataGridView1.Rows.Count == 0)
return;
//实例化一个Excel.Application对象
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
if (excel == null)
{
MessageBox.Show("无法创建Excel对象,可能您的电脑未安装Excel");
return;
}
//让后台执行设置为不可见,为true的话会看到打开一个Excel,然后数据在往里写
excel.Visible = true;
//新增加一个工作簿,Workbook是直接保存,不会弹出保存对话框,加上Application会弹出保存对话框,值为false会报错
excel.Application.Workbooks.Add(true);
//生成Excel中列头名称
for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
if (dataGridView1.Columns[i].Visible == true)
{
excel.Cells[1, i + 1] = dataGridView1.Columns[i].HeaderText;
}
}
//把DataGridView当前页的数据保存在Excel中
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
//System.Windows.Forms.Application.DoEvents();
for (int j = 0; j < dataGridView1.Columns.Count; j++)
{
if (dataGridView1.Columns[j].Visible == true)
{
if (dataGridView1[j, i].ValueType == typeof(string))
{
excel.Cells[i + 2, j + 1] = "'" + dataGridView1[j, i].Value.ToString();
}
else
{
excel.Cells[i + 2, j + 1] = dataGridView1[j, i].Value;
}
}
}
//System.Windows.Forms.Application.DoEvents();
}
//设置禁止弹出保存和覆盖的询问提示框
excel.DisplayAlerts = false;
excel.AlertBeforeOverwriting = false;
//保存工作簿
//excel.Application.Workbooks.Add(true).Save();
//保存excel文件
excel.Save("D:\\1.xls");
//确保Excel进程关闭
excel.Quit();
excel = null;
GC.Collect();//如果不使用这条语句会导致excel进程无法正常退出,使用后正常退出
MessageBox.Show(this, "文件已经成功导出!", "信息提示");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "错误提示");
}
}
方法二:
private void btnExport_Click(object sender, EventArgs e)
{
#region
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Execl files (*.xls)|*.xls|*.xlsx";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.CreatePrompt = true;
saveFileDialog.Title = "Export Excel File";
saveFileDialog.ShowDialog();
if (saveFileDialog.FileName == "")
return;
Stream myStream;
myStream = saveFileDialog.OpenFile();
StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
string str = "";
try
{
for (int i = 0; i < dgvRole.ColumnCount; i++)
{
if (i > 0)
{
str += "\t";
}
str += dgvRole.Columns[i].HeaderText;
}
sw.WriteLine(str);
for (int j = 0; j < dgvRole.Rows.Count; j++)
{
string tempStr = "";
for (int k = 0; k < dgvRole.Columns.Count; k++)
{
if (k > 0)
{
tempStr += "\t";
}
tempStr += dgvRole.Rows[j].Cells[k].Value == null ? "" : dgvRole.Rows[j].Cells[k].Value.ToString();
}
sw.WriteLine(tempStr);
}
sw.Close();
myStream.Close();
}
catch (Exception ex)
{
//MessageBox.Show(ex.ToString());
}
finally
{
sw.Close();
myStream.Close();
}
#endregion
}
在网上也是参考的别的做法,亲测可行,留此纪录。我把代码已上传至本博客,链接如下:
https://download.youkuaiyun.com/download/honey_jessica/11184915