zoukankan      html  css  js  c++  java
  • winform datagridview 导出excel

    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("导出文件时出错,文件可能正被打开! " + 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
            }
        }
    }

  • 相关阅读:
    动态生成 Excel 文件供浏览器下载的注意事项
    JavaEE 中无用技术之 JNDI
    CSDN 泄露用户密码给我们什么启示
    刚发布新的 web 单点登录系统,欢迎下载试用,欢迎提建议
    jQuery jqgrid 对含特殊字符 json 数据的 Java 处理方法
    一个 SQL 同时验证帐号是否存在、密码是否正确
    PostgreSQL 数据库在 Windows Server 2008 上安装注意事项
    快速点评 Spring Struts Hibernate
    Apache NIO 框架 Mina 使用中出现 too many open files 问题的解决办法
    解决 jQuery 版本升级过程中出现 toLowerCase 错误 更改 doctype
  • 原文地址:https://www.cnblogs.com/glj1203/p/3527699.html
Copyright © 2011-2022 走看看