using System;
using System.Linq;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
namespace WinFormExcel
{
static class ExtensionMethod
{
/// <summary>
/// 用 DataGridView 控件内容导出 Excel 报表。
/// </summary>
/// <param name="gridView"></param>
/// <param name="caption"></param>
#region
public static void PrintToExcel(this DataGridView gridView, string caption)
{
Excel.Application xls = new Excel.Application();
try
{
Excel.Workbook book = xls.Workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
Excel.Worksheet sheet = book.ActiveSheet as Excel.Worksheet;
xls.Visible = true;
book.Password = "jinzhexian";
sheet.Name = caption; // 工作表名。
Excel.Range range = sheet.get_Range("B1", Type.Missing).get_Resize(2, gridView.ColumnCount);
range.MergeCells = true; // 合并单元格。
range.Font.Size = 16;
range.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter; // 文本水平居中。
range.Value2 = caption; // 表标题。
range = range.get_Offset(1, 0).get_Resize(1, gridView.ColumnCount);
range.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter; // 文本水平居中。
range.Value2 = gridView.Columns.Cast<DataGridViewColumn>().Select(sm => sm.HeaderText).ToArray(); // 列标题。
foreach (DataGridViewRow row in gridView.Rows)
{
range = range.get_Offset(1, 0);
range.Value2 = row.Cells.Cast<DataGridViewCell>().Select(sm => sm.FormattedValue).ToArray();
}
range = range.get_Offset(2, 0);
range.MergeCells = true; // 合并单元格。
range.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter; // 文本水平居中。
range.Value2 = string.Format("打印日期: {0:yyyy'年'M'月'd'日'}", DateTime.Today);
range.EntireColumn.AutoFit(); // 自动调整列宽。
sheet.get_Range("A4", Type.Missing).Select();
xls.SendKeys("%WFF", true); // 冻结拆分窗格 Microsoft Office 2003(%WF), 2007(%WFF)。
}
catch
{
xls.Quit();
}
finally
{
xls = null;
GC.Collect();
}
}
#endregion
}
}