using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.Office.Core;
using EXCEL = Microsoft.Office.Interop.Excel;
//数据库支持
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Threading;
/// <summary>
/// 把DataGridView数据导出到Excel(注:pb_Excel是一个进度条控件)
/// </summary>
/// <param name="fileName">导出后的文件名.xls(中间可以修改)</param>
/// <param name="myDGV">要导出的DataGridView对象</param>
<span style="white-space:pre"> </span>private void ExportExcel(string fileName, DataGridView myDGV)
{
string saveFileName = "";
SaveFileDialog saveDialog = new SaveFileDialog();
saveDialog.DefaultExt = "xls";
saveDialog.Filter = "Excel文件|*.xls";
saveDialog.FileName = fileName;
saveDialog.ShowDialog();
saveFileName = saveDialog.FileName;
if (saveFileName.IndexOf(":") < 0) return; //被点了取消
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
if (xlApp == null)
{
MessageBox.Show("无法创建Excel对象,可能您的机子未安装Excel");
return;
}
Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;
Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];//取得sheet1
//进度条的使用
pb_Excel.Refresh();
pb_Excel.Visible = true;
pb_Excel.Value = 1;
pb_Excel.Minimum = 1;
pb_Excel.Maximum = myDGV.RowCount;
pb_Excel.Step = 1;
//写入标题
for (int i = 0; i < myDGV.ColumnCount; i++)
{
worksheet.Cells[1, i + 1] = myDGV.Columns[i].HeaderText;
}
//写入数值
for (int r = 0; r < myDGV.Rows.Count; r++)
{
pb_Excel.PerformStep();
for (int i = 0; i < myDGV.ColumnCount; i++)
{
worksheet.Cells[r + 2, i + 1] = myDGV.Rows[r].Cells[i].Value;
}
System.Windows.Forms.Application.DoEvents();
}
//pb_Excel.Visible = false;
pb_Excel.Value = 1;
worksheet.Columns.EntireColumn.AutoFit();//列宽自适应
if (saveFileName != "")
{
try
{
workbook.Saved = true;
workbook.SaveCopyAs(saveFileName);
}
catch (Exception ex)
{
MessageBox.Show("导出文件时出错,文件可能正被打开!\n" + ex.Message);
}
}
xlApp.Quit();
GC.Collect();//强行销毁
//MessageBox.Show("文件: " + FileName + ".xls 保存成功", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
MessageBox.Show("文件保存成功", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
原文地址:<a target=_blank href="http://blog.sina.com.cn/s/blog_62cd5a980101905a.html">http://blog.sina.com.cn/s/blog_62cd5a980101905a.html</a>