DataGridView导出excel(转载)

本文参考网友江边孤岛(感谢原作者)的《WinForm中DataGrid扩展类 - 快速导出Excel文件,带保存对话框,并杀死进程。相对完美的解决方案!》(url: http://blog.csdn.net/jbgh608/archive/2007/08/29/1763517.aspx  )而写,但本文是DataGridView导出Excel,DataGridView中的隐含列不导出。在贴出代码前几点说明如下:

1、添加Microsoft Excel 11.0 Object Library的引用后,在项目的引用列表中会多出3个引用项,分别是Excel、Microsoft.Office.Core、VBIDE;(当然添加Microsoft Word 11.0 Object Library的引用后,在项目的引用列表中也会多出3个引用项,分别是Word、Microsoft.Office.Core、VBIDE,即第一个是变化的,后两个是相同的,但如果你添加Microsoft Office 11.0 Object Library,那么仅有Microsoft.Office.Core)

微软的Office对象库包含:
Microsoft Access 11.0 Object Library
Microsoft Graph 11.0 Object Library
Microsoft Excel 11.0 Object Library
Microsoft Office 11.0 Object Library
Microsoft Outlook 11.0 Object Library
Microsoft PowerPoint 11.0 Object Library
Microsoft Word 11.0 Object Library

对于上面的对象库,微软是否提供了API文档?本人尚未找到。

2、文件是否已经打开的判断,网上很多是以独享的方式打开文件,如果出现异常则说明文件已经在使用中,我觉得这个判断不理想,不知道是否有更好的处理方法?

3、实测中发现执行设置Excel字体大小和将字体设置为粗体的语句耗时较长,不知道是本人机器环境的原因还是Excel的普遍问题?

4、原文杀死excel进程的处理方法并不得当,会将所有正在使用的excel都关闭掉。但导出excel确实会增加excel的进程,不妥。

一下是代码

调用方法为:

Export export  =   new  Export();
export.ToExcel(
this this .dgInOut,  " 收支账 " );

导出类源码:

using  System;
using  System.Collections.Generic;
using  System.Windows.Forms;
using  System.Text;
using  System.Diagnostics;
using  System.IO;
using  Microsoft.Office.Interop.Excel;

namespace  ST.FI
{
    
public class Export
    
{
        
//记录保存文件的名称(含路径)
        private string FullFileName = string.Empty;

        
#region 保存对话框
        
private bool SaveFileDialog()
        
{
            SaveFileDialog saveFileDialog1 
= new SaveFileDialog();
            saveFileDialog1.Filter 
= "excel files(*.xls)|*.xls";//excel files(*.xls)|*.xls|All files(*.*)|*.*
            saveFileDialog1.FilterIndex = 0;
            saveFileDialog1.RestoreDirectory 
= true;

            
//标志变量、返回结果
            bool IsOK=false;
            
bool result = false;

            
//文件已经存在,需要重新输入文件名时,循环打开保存对话框
            while (!IsOK)
            
{
                
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                
{
                    
//修改给定的文件名,增加时间信息
                    FullFileName = saveFileDialog1.FileName.Insert(saveFileDialog1.FileName.LastIndexOf("/"+ 1, DateTime.Now.ToString("yyyyMMdd"));

                    
//文件信息,判断文件是否已经存在;
                    
//遗留问题:文件是否已经打开本想在此处判断,但没有找到合适的方法,如果你有合适的方法,请赐教cm909@tom.com
                    FileInfo fi = new FileInfo(FullFileName);
                    
if (fi.Exists)
                    
{
                        DialogResult dr 
= MessageBox.Show("文件已经存在,是否覆盖现有文件?""系统信息", MessageBoxButtons.YesNoCancel);
                        
if (dr == DialogResult.Yes)
                            
//如果覆盖现有文件
                        {
                            IsOK 
= true;
                            result 
= true;
                        }

                        
else if (dr == DialogResult.Cancel)
                            
//如果取消操作
                        {
                            IsOK 
= true;
                            result 
= false;
                        }

                        
//如果不覆盖现有文件,则IsOK仍为false,实现循环
                    }

                }

            }


            
return result;
        }



        
#endregion


        
#region 导出Excel
        
public void ToExcel(Form ParentWindow, DataGridView ExportGrid,  string p_ReportName)
        
{
            
//如果网格尚未数据绑定
            if(ExportGrid==null)
                
return;

            
// 列索引,行索引
            int colIndex = 0;
            
int rowIndex = 0;
            
//总可见列数,总可见行数
            int colCount = ExportGrid.Columns.GetColumnCount(DataGridViewElementStates.Visible);
            
int rowCount = ExportGrid.Rows.GetRowCount(DataGridViewElementStates.Visible);

            
//如果DataGridView中没有行,返回
            if (rowCount == 0)
                
return;

            
//保存对话框
            if (!SaveFileDialog())
                
return;

            ParentWindow.Cursor 
= Cursors.WaitCursor;
            
// 创建Excel对象                    
            Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
            
if (xlApp == null)
            
{
                MessageBox.Show(
"Excel无法启动","系统信息");
                
return;
            }

            
// 创建Excel工作薄
            Microsoft.Office.Interop.Excel.Workbook xlBook = xlApp.Workbooks.Add(true);
            Microsoft.Office.Interop.Excel.Worksheet xlSheet 
= (Microsoft.Office.Interop.Excel.Worksheet)xlBook.Worksheets[1];

            
// 设置标题,实测中发现执行设置字体大小和将字体设置为粗体的语句耗时较长,故注释掉了
            Microsoft.Office.Interop.Excel.Range range = xlSheet.get_Range(xlApp.Cells[11], xlApp.Cells[1, colCount]);
            range.MergeCells 
= true;
            xlApp.ActiveCell.FormulaR1C1 
= p_ReportName;
            
//xlApp.ActiveCell.Font.Size = 20;
            
//xlApp.ActiveCell.Font.Bold = true;
            xlApp.ActiveCell.HorizontalAlignment = Microsoft.Office.Interop.Excel.Constants.xlCenter;

            
// 创建缓存数据
            object[,] objData = new object[rowCount + 1, colCount];
            
// 获取列标题,隐藏的列不处理
            for (int i = 0; i < ExportGrid.ColumnCount; i++)
            
{
                
if (ExportGrid.Columns[i].Visible)
                    objData[rowIndex, colIndex
++= ExportGrid.Columns[i].HeaderText;
            }

            
// 获取数据,隐藏的列的数据忽略
            for (int i = 1; i <= rowCount; i++)
            
{
                rowIndex
++;
                colIndex 
= 0;
                
for (int j = 0; j < ExportGrid.ColumnCount; j++)
                
{
                    
if (ExportGrid.Columns[j].Visible)
                        objData[rowIndex, colIndex
++= ExportGrid[j,rowIndex - 1].Value.ToString();
                }

                
                System.Windows.Forms.Application.DoEvents();
            }


            
// 写入Excel
            
//xlApp.get_Range(xlApp.Cells[2, 1], xlApp.Cells[2, colIndex]).Font.Bold = true;
            range = xlSheet.get_Range(xlApp.Cells[21], xlApp.Cells[rowCount + 2, colCount]);
            range.Value2 
= objData;

            
// 保存
            try
            
{
                xlApp.Cells.EntireColumn.AutoFit();
                xlApp.Cells.VerticalAlignment 
= Microsoft.Office.Interop.Excel.Constants.xlCenter;
                xlApp.Cells.HorizontalAlignment 
= Microsoft.Office.Interop.Excel.Constants.xlCenter;
                
//xlApp.Visible   =   true;   
                xlBook.Saved = true;
                xlBook.SaveCopyAs(FullFileName);
                MessageBox.Show(
"导出成功!","系统信息");
                ParentWindow.Cursor 
= Cursors.Default;
            }

            
catch
            
{
                MessageBox.Show(
"保存出错,请检查文件是否被正使用!""系统信息");
                
//return false;
            }

            
finally
            
{
                xlApp.Quit();
                GC.Collect();
                
//KillProcess("excel");
            }

            
//return true;
        }

        
#endregion


        
#region 杀死进程
        
private void KillProcess(string processName)
        
{
            System.Diagnostics.Process myproc 
= new System.Diagnostics.Process();
            
//得到所有打开的进程 
            try
            
{
                
foreach (Process thisproc in Process.GetProcessesByName(processName))
                
{
                    thisproc.Kill();
                }

            }

            
catch (Exception Exc)
            
{
                
throw new Exception("", Exc);
            }

        }

        
#endregion
 
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值