c#高效率导出多维表头excel的实例代码

代码如下:

[DllImport("User32.dll", CharSet = CharSet.Auto)]
        public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int ID);
        private void ExportToExcel(string fielName)
        {
            //实例化一个Excel.Application对象   
            Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();

try
            {
                if (dgv_Result.DataSource == null)
                    return;
                if (dgv_Result.Rows.Count == 0)
                    return;

//新增加一个工作簿,Workbook是直接保存,不会弹出保存对话框,加上Application会弹出保存对话框,值为false会报错   
                Microsoft.Office.Interop.Excel.Workbook xlBook = excel.Workbooks.Add(true);

//1.添加表头
                excel.Cells[1, 1] = tyclass;
                for (int i = 0; i < dgv_Result.Columns.Count; i++)
                {

excel.Cells[2, i + 1] = dgv_Result.Columns[i].Name;
                }

#region 2.实现Excel多维表头 采用合并单元格的方式
                Microsoft.Office.Interop.Excel.Worksheet sheet = (Microsoft.Office.Interop.Excel.Worksheet)xlBook.ActiveSheet;
                Microsoft.Office.Interop.Excel.Range excelRange = sheet.get_Range(sheet.Cells[1, 1], sheet.Cells[1, 2]);
                Microsoft.Office.Interop.Excel.Range excelRange1 = sheet.get_Range(sheet.Cells[1, 3], sheet.Cells[1, 4]);
                Microsoft.Office.Interop.Excel.Range excelRange2 = sheet.get_Range(sheet.Cells[1,5], sheet.Cells[1, 6]);
                Microsoft.Office.Interop.Excel.Range excelRange3 = sheet.get_Range(sheet.Cells[1,7], sheet.Cells[1, 8]);
                Microsoft.Office.Interop.Excel.Range excelRange4 = sheet.get_Range(sheet.Cells[1, 2], sheet.Cells[1, 3]);
                Microsoft.Office.Interop.Excel.Range excelRange5 = sheet.get_Range(sheet.Cells[1, 6], sheet.Cells[1, 7]);
                Microsoft.Office.Interop.Excel.Range excelRange6 = sheet.get_Range(sheet.Cells[1, 4], sheet.Cells[1,5]);
                excelRange.Merge(excelRange.MergeCells);
                excelRange1.Merge(excelRange1.MergeCells);
                excelRange4.Merge(excelRange4.MergeCells);
                excelRange2.Merge(excelRange2.MergeCells);
                excelRange3.Merge(excelRange3.MergeCells);
                excelRange5.Merge(excelRange5.MergeCells);
                excelRange6.Merge(excelRange6.MergeCells);
                Microsoft.Office.Interop.Excel.Range columnRange = sheet.get_Range("A1", "H2");   //得到  Range 范围  A-H 表示1-8列,1-2表示跨几行
                 columnRange.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
                 columnRange.Font.Size = 10;
                 columnRange.Font.Bold = true;

#endregion

#region 3.添加行数据,直接给Range赋值可提高效率

Microsoft.Office.Interop.Excel.Range range = sheet.get_Range("A3", "H" + (dgv_Result.Rows.Count + 2).ToString());   //得到  Range 范围
                string[,] AryData = new string[dgv_Result.Rows.Count-1, dgv_Result.Columns.Count];
                for (int i = 0; i < dgv_Result.Rows.Count - 1; i++)
                {
                    for (int j = 0; j < dgv_Result.Columns.Count; j++)
                    {

AryData[i,j] = dgv_Result.Rows[i].Cells[j].Value.ToString();
                    }
                }
                range.Value2 = AryData;
                range.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
                #endregion

sheet.Cells.Columns.AutoFit();//设置Excel表格的  列宽
                excel.SheetsInNewWorkbook = 1;//设置Excel单元格对齐方式
                excel.DisplayAlerts = false; //设置禁止弹出保存和覆盖的询问提示框   
                excel.AlertBeforeOverwriting = false;
                //保存excel文件   
                xlBook.SaveAs(fielName, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                MessageBox.Show("导出成功!", "提示");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误提示");
            }
            finally
            {
                IntPtr pt = new IntPtr(excel.Hwnd);
                int k = 0;
                GetWindowThreadProcessId(pt, out k);
                System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(k);
                p.Kill();

}

}

(0)

相关推荐

  • C#导入导出EXCEL文件的代码实例

    复制代码 代码如下: using System;using System.Data;using System.Data.OleDb; namespace ZFSoft.Joint{    public class ExcelIO    {        private int _ReturnStatus;        private string _ReturnMessage; /// <summary>        /// 执行返回状态        /// </summary&g

  • c#生成excel示例sql数据库导出excel

    复制代码 代码如下: using System;using System.Collections.Generic;using System.Linq;using System.Text;using Microsoft.Office.Interop.Excel;using System.Reflection; namespace ListToExcel{    class Program    {        static List<objtype> objs = new List<ob

  • C#与SQL连接:GridView控件对数据库的操作

    GridView和DataGrid的异同 GridView 是 DataGrid的后继控件,在.net framework 2 中,虽然还存在DataGrid,但是GridView已经走上了历史的前台,取代DataGrid的趋势已是势不可挡.GridView和DataGrid功能相似,都是在web页面中显示数据源中的数据,将数据源中的一行数据,也就是一条记录,显示为在web页面上输出表格中的一行. GridView相对于DataGrid来说,具有如下优势,功能上更加丰富,因为提供了智能标记面板(

  • c#读取xml文件到datagridview实例

    复制代码 代码如下: using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using System.IO;using System.Xml;using System.Xml.Linq; namespa

  • C#使用RenderControl将GridView控件导出到EXCEL的方法

    本文实例展示了C#使用RenderControl将GridView控件导出到EXCEL的方法,是非常实用的一个功能,分享给大家供大家参考.具体如下: 主要功能代码如下: // 把GridView输出到Excel文件 private void ExportExcel(GridView gridView, string title, string title2, string fileName) { int nHideCols = 0; //如果不想输出出某列,将Visible设为false即可 f

  • C# DataGridView添加新行的2个方法

    可以静态绑定数据源,这样就自动为DataGridView控件添加 相应的行.假如需要动态为DataGridView控件添加新行,方法有很多种,下面简单介绍如何为DataGridView控件动态添加新行的两种方 法: 方法一: 复制代码 代码如下: int index=this.dataGridView1.Rows.Add();this.dataGridView1.Rows[index].Cells[0].Value = "1"; this.dataGridView1.Rows[inde

  • C# DatagridView常用操作汇总

    本文汇总了C#中DatagridView的常用操作,有助于读者加深对C# DatagridView用法的理解,具体如下: 1.(最基本的技巧).获取某列中的某行(某单元格)中的内容 this.currentposition = this.dataGridView1.BindingContext [this.dataGridView1.DataSource, this.dataGridView1.DataMember].Position; bookContent = this.database.d

  • c#利用Excel直接读取数据到DataGridView

    在winform里拖入一个datagridview控件,跟一个openfiledialog控件 复制代码 代码如下: using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using Microsoft.Office.Core;using Excel=Mi

  • c#获取gridview的值代码分享

    GridView设置如下: 复制代码 代码如下: <asp:GridView ID="GridViewlb" runat="server" AutoGenerateColumns="False" CssClass="tabblue" ShowCellToolTip=" True"              EmptyDataText="暂时没有记录!" Width="10

  • C#精髓 GridView72大绝技 学习gridview的朋友必看

    快速预览:GridView无代码分页排序GridView选中,编辑,取消,删除GridView正反双向排序GridView和下拉菜单DropDownList结合GridView和CheckBox结合鼠标移到GridView某一行时改变该行的背景色方法一鼠标移到GridView某一行时改变该行的背景色方法二GridView实现删除时弹出确认对话框GridView实现自动编号GridView实现自定义时间货币等字符串格式GridView实现用"..."代替超长字符串GridView一般换行

  • C# WinForm导出Excel方法介绍

    .NET开发人员首选的方法,通过COM组件调用Office软件本身来实现文件的创建和读写,但是数据量较大的时候异常缓慢:如下代码所示已经做了优化,将一个二维对象数组赋值到一个单元格区域中(下面的代码中只能用于导出列数不多于26列的数据导出): Office PIA 复制代码 代码如下: public static void ExportToExcel(DataSet dataSet, string outputPath){    Excel.ApplicationClass excel = ne

随机推荐