---恢复内容开始---

using Microsoft.Office.Interop.Excel; 
针对office 2003需添加引用Microsoft   Excel   11.0   Object   Library

如添加之后还不能用再using microsoft.office.core和excel

引用的dll为

Interop.Microsoft.Office.Core.dll

Interop.Excel.dll

Excel导出类:

using System;
using System.IO;
using System.Data;
using Microsoft.Office.Interop.Excel;
 
    ///   <summary> 
    ///   导出Excal文件
    ///   </summary> 
public class ImportExcel
{
    private string title;
    private string rpt_name;
    private string outFilePath;
    private System.Data.DataTable dt;
    private System.Data.DataTable outTable;
 
    public ImportExcel()
    {
 
    }
 
    ///   <summary> 
    ///   设置Excel标题 
    ///   </summary> 
    public string rptName
    {
        get
        {
            return title;
        }
        set
        {
            title = value;
        }
    }
 
    ///   <summary> 
    ///   需要导入EXCEL的表 
    ///   </summary> 
    public System.Data.DataTable RptData
    {
        get
        {
            return dt;
        }
        set
        {
            dt = value;
        }
    }
 
    ///   <summary> 
    ///   设置输出文件的存放位置 
    ///   </summary> 
    public string OutFilePath
    {
        get
        {
            return outFilePath;
        }
        set
        {
            outFilePath = value;
        }
    }
 
    ///   <summary> 
    ///   构造函数,使用该类需传入Excel标题,DataTable,文件的存放路径 
    ///   </summary> 
    ///   <param   name="rptName">要设置的Excel标题</param> 
    ///   <param   name="dtable">要填充Excel的表</param> 
    ///   <param   name="FilePath">要存放的路径</param> 
    public ImportExcel(string rptName, System.Data.DataTable dtable, string file_path)
    {
        rpt_name = rptName;
        outTable = dtable;
        outFilePath = file_path;
 
        try
        {
            this.InsertExcel();
        }
        catch (Exception e)
        {
            throw new Exception(e.Message);
        }
    }
 
    ///   <summary> 
    ///   该函数向Excel表中插入记录,要插入的数据为一个内存表.其中内存表中的列名为表中的列名 
    ///   该函数所使用的动态连接库Excel.dll,Office.dll,VBIDE.dll. 
    ///   </summary> 
    public void InsertExcel()
    {
        int col_count = 0;
        int row_count = 0;
        int k = 0;
        int l = 0;
 
        //检查文件是否存在 
        if (File.Exists(outFilePath))
        {
            throw new Exception("文件已存在,创建失败!");
        }
 
        Microsoft.Office.Interop.Excel.ApplicationClass rptApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
 
        rptApp.Application.Workbooks.Add(true);
 
        rptApp.Visible = false;
 
        object missing = System.Reflection.Missing.Value;
 
        Microsoft.Office.Interop.Excel.Workbook rptBook = rptApp.Workbooks[1];
        Microsoft.Office.Interop.Excel.Worksheet rptSheet = (Microsoft.Office.Interop.Excel.Worksheet)rptBook.ActiveSheet;
 
 
        //设置报表的标题 
        rptSheet.Cells[1, 1] = rpt_name;
 
        //插入列标题 
        foreach (DataColumn col in outTable.Columns)
        {
            col_count++;
            rptSheet.Cells[2, col_count] = col.ColumnName.ToString();
        }
        //设置列标题格式
        rptSheet.get_Range(rptSheet.Cells[2, 1],rptSheet.Cells[2, col_count]).Font.Bold = true; // 是否加粗:是
 
        //设置单元格的格式 
        foreach (DataRow dr in outTable.Rows)
        {
            row_count++;
            col_count = 0;
            foreach (DataColumn col in outTable.Columns)
            {
                col_count++;
                if (col.DataType == System.Type.GetType("System.String"))
                {
                    rptSheet.get_Range(rptSheet.Cells[1, 1], rptSheet.Cells[row_count + 2, col_count]).NumberFormatLocal = "@";
                }
                else if (col.DataType == System.Type.GetType("System.DateTime"))
                {
                    rptSheet.get_Range(rptSheet.Cells[1, 1], rptSheet.Cells[row_count + 2, col_count]).NumberFormatLocal = "yyyy-m-d";
                }
            }
        }
 
        //向报表插入记录 
        for (int i = 0; i < outTable.Rows.Count; i++)
        {
            for (int j = 0; j < outTable.Columns.Count; j++)
            {
                k = i + 3;
                l = j + 1;
                rptSheet.Cells[k, l] = outTable.Rows[i][j].ToString();
                rptSheet.get_Range(rptSheet.Cells[1, l], rptSheet.Cells[1, l]).Borders.LineStyle = 7;
                rptSheet.get_Range(rptSheet.Cells[2, l], rptSheet.Cells[2, l]).Borders.LineStyle = 1;
                rptSheet.get_Range(rptSheet.Cells[k, l], rptSheet.Cells[k, l]).Borders.LineStyle = 1;
            }
        }
 
        //设置标题的格式 
        rptSheet.get_Range(rptSheet.Cells[1, 1], rptSheet.Cells[1, 1]).Font.Bold = true;
        rptSheet.get_Range(rptSheet.Cells[1, 1], rptSheet.Cells[1, 1]).Font.Size = 22;
 
        //设置报表的标题为跨列居中合并单元格 
        rptSheet.get_Range(rptSheet.Cells[1, 1], rptSheet.Cells[1, col_count]).Select();
        rptSheet.get_Range(rptSheet.Cells[1, 1], rptSheet.Cells[1, col_count]).HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenterAcrossSelection;
 
        //设置报表表格为最适应宽度 
        rptSheet.get_Range(rptSheet.Cells[1, 1], rptSheet.Cells[row_count, col_count]).Select();
        rptSheet.get_Range(rptSheet.Cells[1, 1], rptSheet.Cells[row_count, col_count]).Columns.AutoFit();
 
        //另存文件到指定路径下 
        rptBook.SaveAs(outFilePath, missing, missing, missing, missing, missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, missing, missing, missing, missing, missing);
        //关闭文件 
        rptBook.Close(false, outFilePath, true);
        rptApp.Quit();
        System.Runtime.InteropServices.Marshal.ReleaseComObject(rptSheet);
        System.Runtime.InteropServices.Marshal.ReleaseComObject(rptBook);
        System.Runtime.InteropServices.Marshal.ReleaseComObject(rptApp);
        //强制释放无用资源 
        GC.Collect();
    }
}

错误:检索 COM 类工厂中 CLSID 为 {00024500-0000-0000-C000-000000000046} 的组件时失败,原因是出现以下错误: 80070005。

解决方法一:
控制面板-》管理工具-》组件服务-》计算机-》我的电脑-》DCom配置-》找到Microsoft Excel 应用程序
之后
单击属性打开此应用程序的属性对话框。  
2. 单击标识选项卡,然后选择交互式用户。 
3.单击"安全"选项卡,分别在"启动和激活权限"和"访问权限"组中选中"自定义",然后
自定义->编辑->添加ASP.NET账户和IUSER_计算机名: 需要本地激活,和本地访问两个权限

4."标识"选项卡 选择交互式用户

---恢复内容结束---

asp.net(C#) Excel导出类 导出.xls文件的更多相关文章

  1. 用javah 导出类的头文件, 常见的错误及正确的使用方法

    ******************************************************************************** 用javah 导出类的头文件, 常见的 ...

  2. Java解析Excel工具类(兼容xls和xlsx)

    依赖jar <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml&l ...

  3. Asp .Net Core Excel导入和导出

    ASP .Net Core使用EPPlus实现Api导入导出,这里使用是EPPlus 4.5.2.1版本,.Net Core 2.2.在linux上运行的时候需要安装libgdiplus . 下面我们 ...

  4. C#:导入Excel通用类(Xls格式)

    PS:在CSV格式和XLSX格式中有写到通用调用的接口和引用的插件,所以在这个xls格式里面并没有那么详细,只是配上xls通用类. 一.引用插件NPOI.dll.NPOI.OOXML.dll.NPOI ...

  5. Android 导入导出CSV,xls文件 .

    1 . http://www.bangchui.org/read.php?tid=62 2 .http://blog.csdn.net/xinzheng_wang/article/details/77 ...

  6. winform NPOI excel 导出并选择保存文件路径

    public void ExcelOp(DataGridView gdv,ArrayList selHead) { if (selHead.Count==0) { MessageBox.Show(&q ...

  7. php中使用PHPExcel读写excel(xls)文件的方法

    首先从GitHub上下载 excel的相关类库 下载地址:https://github.com/PHPOffice/PHPExcel 以下是从excel中获取数据 <?php /** * * @ ...

  8. 导入导出Excel工具类ExcelUtil

    前言 前段时间做的分布式集成平台项目中,许多模块都用到了导入导出Excel的功能,于是决定封装一个ExcelUtil类,专门用来处理Excel的导入和导出 本项目的持久化层用的是JPA(底层用hibe ...

  9. MVC NPOI Linq导出Excel通用类

    之前写了一个模型导出Excel通用类,但是在实际应用中,可能不是直接导出模型,而是通过Linq查询后获取到最终结果再导出 通用类: public enum DataTypeEnum { Int = , ...

随机推荐

  1. Redis从基础命令到实战之列表类型(List)

    经过上一篇基于Redis散列类型的改造后,实战练习中的商品管理已经具备了增加.修改整体.修改部分属性和分页查询功能,但仍然不支持删除商品的功能.这是因为商品总数是以一个自增数字记录的,且关联了新商品k ...

  2. ruby 简介

    Ruby 是一个注重均衡的语言,它的发明者松本行弘 Yukihiro “Matz” Matsumoto,混合了他喜欢的语言(Perl. Smalltalk. Eiffel. Ada 和 Lisp ) ...

  3. JavaScript DOM编程艺术读书笔记(四)

    第十章 实现动画效果 var repeat = "moveElement('"+elementID+"',"+final_x+","+fin ...

  4. 关于z-index

    某些情况下z-index设置多高都不起作用. 1.这种情况有三个前提条件:父标签position属性为relative:问题标签无position属性(不包括static):问题标签含有浮动(floa ...

  5. nodejs学习笔记(一)

    终于开始学NodeJs了 说说遇到的问题吧 1.安装express npm install -g express(按道理说,这个全局安装是没问题的,但他就是出问题了) 解决方案: 来源:http:// ...

  6. C#检测键盘输入

    void Update(){     if (Input.GetKey(KeyCode.W))     {          go stread;     }     if (Input.GetKey ...

  7. TDI - Transport Driver Interface

    [TDI - Transport Driver Interface] The Transport Driver Interface or TDI is the protocol understood ...

  8. pdo 事物的处理

  9. jsp js action之间的传值

    1.struts2 action如何向JSP的JS函数传值 action中定义变量public class TestAction extends ActionSupport implements Se ...

  10. shll 变量

    name=zhagnsan age=11 echo $ name $age 赋值号两边没有任何空格.当想取shell变量的值时,需要在变量名前加上$字符,当所赋的值中间含有空格时,要加上引号 函数: ...