DataGridView To Excel

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
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值