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

namespace WebCrawl
{
    class Excel
    {
        [DllImport("User32.dll", CharSet = CharSet.Auto)]
        public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int ID);

public static void ExportExcel( DataGridView myDGV)
        {
            if (myDGV.Rows.Count > 0)
            {

string saveFileName = "";
                //bool fileSaved = false; 
                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.Application _excelApplicatin = null;
                //_excelApplicatin = new Microsoft.Office.Interop.Excel.Application();
                //_excelApplicatin.Visible = true;
                //_excelApplicatin.DisplayAlerts = true;

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 
                Microsoft.Office.Interop.Excel.Range range;
                range = (Microsoft.Office.Interop.Excel.Range)worksheet.get_Range("A1","J1");
                range.Select();
                xlApp.ActiveWindow.SplitColumn = 0;
                xlApp.ActiveWindow.SplitRow = 1;
                xlApp.ActiveWindow.FreezePanes = true;
                //xlApp.ActiveWindow.FreezePanes = true;
               
                range.Font.Name = "微软雅黑";
                range.Font.Size = 10;
                range.WrapText = true;
                range.EntireColumn.AutoFit();
                range.HorizontalAlignment = XlHAlign.xlHAlignCenter;
                range.VerticalAlignment = XlVAlign.xlVAlignCenter; ;

//写入标题 
                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-1; r++)
                {

for (int i = 0; i < myDGV.ColumnCount; i++)
                    {
                        worksheet.Cells[r + 2, i + 1] = myDGV.Rows[r].Cells[i].Value;
                       
                    }
                    object Cell1="A"+(r+2)+"";
                    object Cell2="J"+(r+2)+"";
                    worksheet.get_Range(Cell1,Cell2).Font.Name = "微软雅黑";
                    worksheet.get_Range(Cell1,Cell2).Font.Size = 10;
                    worksheet.get_Range("C" + (r + 2) + "", "C" + (r + 2) + "").Font.Color = System.Drawing.Color.FromArgb(128, 0, 128).ToArgb();
                    //worksheet.get_Range("C" + (r + 2) + "", "C" + (r + 2) + "").Interior.Color = System.Drawing.Color.FromArgb(255, 204, 153).ToArgb();
                    //worksheet.get_Range(Cell1, Cell2).WrapText = true;
                    worksheet.get_Range(Cell1, Cell2).HorizontalAlignment = XlHAlign.xlHAlignCenter;
                    worksheet.get_Range(Cell1, Cell2).VerticalAlignment = XlVAlign.xlVAlignCenter;
                    worksheet.get_Range(Cell1, Cell2).Borders.LineStyle = XlLineStyle.xlContinuous;
                    System.Windows.Forms.Application.DoEvents();
                }
                worksheet.Columns.EntireColumn.AutoFit();//列宽自适应 
                //if (Microsoft.Office.Interop.cmbxType.Text != "Notification") 
                //{ 
                //    Excel.Range rg = worksheet.get_Range(worksheet.Cells[2, 2], worksheet.Cells[ds.Tables[0].Rows.Count + 1, 2]); 
                //    rg.NumberFormat = "00000000"; 
                //}

if (saveFileName != "")
                {
                    try
                    {
                        workbook.Saved = true;
                        //workbook.SaveCopyAs(saveFileName);
                        workbook.SaveAs(saveFileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlExcel8, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                       
                        //fileSaved = true; 
                    }
                    catch (Exception ex)
                    {
                        //fileSaved = false; 
                        MessageBox.Show("导出文件时出错,文件可能正被打开!\n" + ex.Message);
                    }

}
                //else 
                //{ 
                //    fileSaved = false; 
                //} 
                xlApp.Quit();
                GC.Collect();//强行销毁
                Kill(xlApp);
                // if (fileSaved && System.IO.File.Exists(saveFileName)) System.Diagnostics.Process.Start(saveFileName); //打开EXCEL 
            }
            else
            {
                return;
            }

}
        public static void Kill(Microsoft.Office.Interop.Excel.Application excel)
        {
            IntPtr t = new IntPtr(excel.Hwnd); //得到这个句柄,具体作用是得到这块内存入口

int k = 0;
            GetWindowThreadProcessId(t, out k); //得到本进程唯一标志k
            System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(k); //得到对进程k的引用
            p.Kill(); //关闭进程k
        }
    }
}

winform datagridview 导出excel的更多相关文章

  1. 从DataGridView导出Excel

    从DataGridView导出Excel的两种情况,不多说,直接记录代码(新建类,直接引用传入参数). using System; using System.Collections.Generic; ...

  2. c# datagridview导出Excel文件 问题

    今天vs2010c#开发做datagridview导出Excel文件时,发现一个问题,和大家探讨一下: 第一种方式:写流的方式 private void button_Excel_Click(obje ...

  3. winform导入导出excel,后台动态添加控件

    思路: 导入: 1,初始化一个OpenFileDialog类 (OpenFileDialog fileDialog = new OpenFileDialog();) 2, 获取用户选择文件的后缀名(s ...

  4. 一个通用的DataGridView导出Excel扩展方法(支持列数据格式化)

    假如数据库表中某个字段存放的值“1”和“0”分别代表“是”和“否”,要在DataGridView中显示“是”和“否”,一般用两种方法,一种是在sql中直接判断获取,另一种是在DataGridView的 ...

  5. C# DataGridView 导出 Excel(根据Excel版本显示选择不同后缀格式xls或xlsx)

    /// <summary> /// DataGridView导出至Excel,解决问题:打开Excel文件格式与扩展名指定格式不一致 /// </summary> /// &l ...

  6. DataGridView 导出Excel (封装)

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.W ...

  7. 【转】c# winform DataGridView导出数据到Excel中,可以导出当前页和全部数据

    准备工作就是可以分页的DataGridView,和两个按钮,一个用来导出当前页数据到Excel,一个用来导出全部数据到Excel 没有使用SaveFileDialog,但却可以弹出保存对话框来 先做导 ...

  8. winform DataGridView 导出到Excel表格 分类: WinForm 2014-07-04 10:48 177人阅读 评论(0) 收藏

    public bool ExportDataGridview(DataGridView gridView)         {             if (gridView.Rows.Count ...

  9. [WinForm]dataGridView导出到EXCEL

    方法一: SaveFileDialog dlg = new SaveFileDialog(); dlg.Filter = "Execl files (*.xls)|*.xls"; ...

随机推荐

  1. Oracle编码

    三.解决数据库乱码原理特辑内容 3.1 前言 在解决数据库乱码问题中,涉及到三个方面的字符集:1.oracel server端的字符集:2.oracle client端的字符集:3.dmp文件的字符集 ...

  2. C#版的 Escape() 和 Unescape()

    Escape: 复制代码 代码如下: public static string Escape(string str) { StringBuilder sb = new StringBuilder(); ...

  3. 【oracle】生成AWR报告

    [第一步]找到awrrpt.sql文件 [ora11g@vm-kvm11820-app ~]$ locate awrrpt.sql /DATA/opt/app/ora11g/product//rdbm ...

  4. DataBase——Mysql的DataHelper

    源帖 https://www.cnblogs.com/youuuu/archive/2011/06/16/2082730.html 保护原帖,尊重技术,致敬工匠! using System; usin ...

  5. 几个NAND/NOR门可以表示一个XOR门?

    这段时间就是在看测试相关的东西,无意之中发现了ISCAS85中有个名词EXOR,愣了一下反应过来应该还是异或门,毕竟叫exclusive-OR gate,其中文档中还提到了一句一个异或门可以由四个与非 ...

  6. 复杂透视表的SQL生成方法

    一般而言,利用表单查看数据时,会从不同的维度来涉及透视表.比如,从产品和时间维度分析销售数据. 当需要从时间维度去分析时,同时希望能有同比,环比数据,那么将时间维度设计成列将极大方便SQL的编写. 如 ...

  7. ccf-路径解析201604-3

    C++没有split函数 但是有一个简单的方法,利用stringstream构建; 然后这道题就很简单啦 还要注意不能用cin 因为有空行的存在 #include <bits/stdc++.h& ...

  8. 关于PHP 缓冲区: ob_star , ob_get_contents

    PHP ob_star ob_get_contents 细说   作者:田园花香  关于PHP 缓冲区 ob_start: 打开输出缓冲区,当缓冲区激活时,所有来自PHP程序的非头文件信息均不会发送, ...

  9. tensorflow 代码阅读

    具体实现: https://github.com/tensorflow/tensorflow/tree/master/tensorflow/core/framework 『深度长文』Tensorflo ...

  10. C# 程序修改config文件后,不重启程序刷新配置ConfigurationManager

    基本共识: ConfigurationManager 自带缓存,且不支持 写入. 如果 通过 文本写入方式 修改 配置文件,程序 无法刷新加载 最新配置. PS. Web.config 除外:Web. ...