C# 将DataGridView控件内容导出到Excel报表

 

using System;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
// 添加引用 -> .NET -> Microsoft.Office.Interop.Excel(2003->11.0, 2007->12.0)

namespace WinFormTable
{
    public partial class FormTable : Form
    {
        #region
        private DataTable table;
        private ChineseLunisolarCalendar lunarCalendar;
        #endregion

        public FormTable()
        {
            #region
            InitializeComponent();
            lunarCalendar = new ChineseLunisolarCalendar(); // 中国阴历。
            table = new DataTable("File");
            table.Locale = CultureInfo.InvariantCulture; // 固定区域。
            DataColumn column = table.Columns.Add("Name", typeof(String));
            table.Columns.Add("Length", typeof(Decimal));
            table.Columns.Add("CreationTime", typeof(DateTime));
            table.Constraints.Add("PK", column, true); // 创建主键。
            table.DefaultView.ApplyDefaultSort = true; // 使用默认排序。
            GridViewStyle();
            #endregion
        }

        #region OnLoad
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            table.BeginLoadData();
            Environment.CurrentDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Recent);
            DirectoryInfo dir = new DirectoryInfo(Environment.CurrentDirectory);
            foreach (FileInfo info in dir.GetFiles("*.lnk"))
            {
                table.Rows.Add(info.Name, info.Length / 1024M, info.CreationTime);
            }
            table.EndLoadData();
            int sw = 28;
            foreach (DataGridViewColumn column in gridView.Columns)
            {
                sw += column.Width;
            }
            this.Width = sw;
            this.Text = dir.Name;
        }
        #endregion

        #region DataGridViewStyle
        private void GridViewStyle()
        {
            DataGridViewTextBoxColumn nameColumn = new DataGridViewTextBoxColumn();
            nameColumn.DataPropertyName = "Name";
            nameColumn.HeaderText = "名称";
            gridView.Columns.Add(nameColumn);
            DataGridViewTextBoxColumn lengthColumn = new DataGridViewTextBoxColumn();
            lengthColumn.DataPropertyName = "Length";
            lengthColumn.HeaderText = "大小";
            lengthColumn.DefaultCellStyle.Format = "#,##0.00 KB";
            lengthColumn.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            gridView.Columns.Add(lengthColumn);
            DataGridViewTextBoxColumn timeColumn = new DataGridViewTextBoxColumn();
            timeColumn.DataPropertyName = "CreationTime";
            timeColumn.HeaderText = "创建时间";
            timeColumn.DefaultCellStyle.Format = "yyyy-MM-dd HH:mm:ss";
            gridView.Columns.Add(timeColumn);
            gridView.AutoGenerateColumns = false; // 禁用自动创建列。
            gridView.AllowUserToAddRows = false; // 隐藏添加行。
            gridView.AllowUserToDeleteRows = false; // 禁用删除行。
            gridView.AllowUserToOrderColumns = false; // 禁用列排序。
            gridView.AllowUserToResizeRows = false; // 禁用调整行高。
            gridView.MultiSelect = false; // 用户仅能选择一个单元格、行或列。
            gridView.ReadOnly = true; // 禁用编辑单元格。
            gridView.RowHeadersVisible = false; // 隐藏包含行标题的列。
            gridView.ShowCellToolTips = true; // 显示工具提示。
            gridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
            gridView.BackgroundColor = SystemColors.Window;
            gridView.BorderStyle = BorderStyle.Fixed3D;
            gridView.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.BottomCenter;
            gridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect; // 通过单击行的标头或是该行所包含的单元格选定整个行。
            gridView.SelectionChanged += new EventHandler(gridView_SelectionChanged);
            gridView.CellToolTipTextNeeded += new DataGridViewCellToolTipTextNeededEventHandler(gridView_CellToolTipTextNeeded);
            gridView.DataSource = table.DefaultView;
        }

        private void gridView_SelectionChanged(object sender, EventArgs e)
        {
            CurrencyManager manager = BindingContext[table.DefaultView] as CurrencyManager;
            toolLabelCount.Text = string.Format("{0} / {1}", manager.Position + 1, manager.Count);
            toolFirstButton.Enabled = toolPreviousButton.Enabled = (manager.Position > 0);
            toolLastButton.Enabled = toolNextButton.Enabled = (manager.Position + 1 < manager.Count);
        }

        private void gridView_CellToolTipTextNeeded(object sender, DataGridViewCellToolTipTextNeededEventArgs e)
        {
            if (e.RowIndex > -1)
                e.ToolTipText = Path.Combine(Environment.CurrentDirectory, table.DefaultView[e.RowIndex][0] as string); // 设置工具提示文本。
        }
        #endregion

        #region
        private void toolStripInfo_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            CurrencyManager manager = BindingContext[table.DefaultView] as CurrencyManager;
            switch (e.ClickedItem.Name)
            {
                case "toolLoadButton":
                    if (folderBrowser.ShowDialog(this) == DialogResult.OK)
                    {
                        table.Clear();
                        table.BeginLoadData();
                        folderBrowser.Description = folderBrowser.SelectedPath;
                        Environment.CurrentDirectory = folderBrowser.SelectedPath;
                        DirectoryInfo dir = new DirectoryInfo(Environment.CurrentDirectory);
                        foreach (FileInfo info in dir.GetFiles())
                        {
                            table.Rows.Add(info.Name, info.Length / 1024M, info.CreationTime);
                        }
                        table.EndLoadData();
                        int sw = 28;
                        foreach (DataGridViewColumn column in gridView.Columns)
                        {
                            sw += column.Width;
                        }
                        this.Width = sw;
                        this.Text = dir.Name;
                    }
                    break;
                case "toolExcelButton":
                    table.AcceptChanges();
                    PrintToExcel(gridView, this.Text);
                    //gridView.PrintToExcel(this.Text);
                    break;
                case "toolXmlButton":
                    FileInfo fi = new FileInfo(Path.Combine(Application.StartupPath, "File.xml"));
                    if (fi.Exists)
                        fi.Attributes = FileAttributes.Normal;
                    using (StreamWriter writer = fi.CreateText())
                    {
                        table.AcceptChanges();
                        table.WriteXml(writer, XmlWriteMode.IgnoreSchema);
                    }
                    System.Diagnostics.Process.Start(fi.FullName);
                    break;
                case "toolFirstButton":
                    manager.Position = 0;
                    break;
                case "toolPreviousButton":
                    --manager.Position;
                    break;
                case "toolNextButton":
                    ++manager.Position;
                    break;
                case "toolLastButton":
                    manager.Position = manager.Count - 1;
                    break;
            }
            toolLabelCount.Text = string.Format("{0} / {1}", manager.Position + 1, manager.Count);
            toolFirstButton.Enabled = toolPreviousButton.Enabled = (manager.Position > 0);
            toolLastButton.Enabled = toolNextButton.Enabled = (manager.Position + 1 < manager.Count);
        }
        #endregion

        #region DataGridView.PrintToExcel
        private void PrintToExcel(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

        #region DateTime
        private void timerInfo_Tick(object sender, EventArgs e)
        {
            Application.CurrentCulture.ClearCachedData();
            DateTime solar = DateTime.Now;
            int month = lunarCalendar.GetMonth(solar);
            int leapMonth = lunarCalendar.GetLeapMonth(lunarCalendar.GetYear(solar));
            if (0 < leapMonth && leapMonth <= month)
                --month;
            statusLabelTime.Text = string.Format("{0:F} [{1} {2:00}]", solar, DateTimeFormatInfo.CurrentInfo.MonthNames[month - 1], lunarCalendar.GetDayOfMonth(solar));
        }
        #endregion
    }
}

发布了29 篇原创文章 · 获赞 25 · 访问量 10万+

猜你喜欢

转载自blog.csdn.net/woguyanli/article/details/7275979