Excel文件导入导出,需引用Microsoft Excel 11.0 Object Library

///////////////////////////////////////////////////////////////////////////
//Purpose:Excel文件导入导出,需引用Microsoft Excel 11.0 Object Library
//Author: Dangmy
//Date: 2007-03-09
//Version: 1.0
///////////////////////////////////////////////////////////////////////////

public class ExcelIO
{
     private int _ReturnStatus;
     private string _ReturnMessage;

     /// <summary>
     /// 执行返回状态
     /// </summary>
     public int ReturnStatus
     {
         get{return _ReturnStatus;}
     }

     /// <summary>
     /// 执行返回信息
     /// </summary>
     public string ReturnMessage
     {
         get{return _ReturnMessage;}
     }

     public ExcelIO()
     {
     }

     /// <summary>
     /// 导入EXCEL到DataSet
     /// </summary>
     /// <param name="fileName">Excel全路径文件名</param>
     /// <returns>导入成功的DataSet</returns>
     public DataSet ImportExcel(string fileName)
     {
         //判断是否安装EXCEL
         Excel.Application xlApp=new Excel.ApplicationClass();
         if(xlApp==null)
         {
             _ReturnStatus = -1;
             _ReturnMessage = "无法创建Excel对象,可能您的计算机未安装Excel";
             return null;
         }       

         //判断文件是否被其他进程使用
         Excel.Workbook workbook;
         try
         {
             workbook = xlApp.Workbooks.Open(fileName,0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, 0, true, 1, 0);
         }
         catch
         {
             _ReturnStatus = -1;
             _ReturnMessage = "Excel文件处于打开状态,请保存关闭";
             return null;
         }       

         //获得所有Sheet名称
         int n = workbook.Worksheets.Count;
         string[] SheetSet = new string[n];
         System.Collections.ArrayList al = new System.Collections.ArrayList();
         for(int i=1; i<=n; i++)
         {
             SheetSet[i-1] = ((Excel.Worksheet)workbook.Worksheets[i]).Name;
         }

         //释放Excel相关对象
         workbook.Close(null,null,null);
         xlApp.Quit();
         if(workbook != null)
         {
             System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
             workbook = null;
         }
         if(xlApp != null)
         {
             System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
             xlApp = null;
         }
         GC.Collect();

         //把EXCEL导入到DataSet
         DataSet ds = new DataSet();
         string connStr = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = "+ fileName +";Extended Properties=Excel 8.0" ;
         using(OleDbConnection conn = new OleDbConnection (connStr))
         {
             conn.Open();
             OleDbDataAdapter da;
             for(int i=1; i<=n; i++)
             {
                 string sql = "select * from ["+ SheetSet[i-1] +"$] ";
                 da = new OleDbDataAdapter(sql,conn);
                 da.Fill(ds,SheetSet[i-1]);
                 da.Dispose();
             }
             conn.Close();
             conn.Dispose();
         }
         return ds;
     }

     /// <summary>
     /// 把DataTable导出到EXCEL
     /// </summary>
     /// <param name="reportName">报表名称</param>
     /// <param name="dt">数据源表</param>
     /// <param name="saveFileName">Excel全路径文件名</param>
     /// <returns>导出是否成功</returns>
     public bool ExportExcel(string reportName,DataTable dt,string saveFileName)
     {
         if(dt==null)
         {
             _ReturnStatus = -1;
             _ReturnMessage = "数据集为空!";
             return false;
         }

         bool fileSaved=false;
         Excel.Application xlApp=new Excel.ApplicationClass();
         if(xlApp==null)
         {
             _ReturnStatus = -1;
             _ReturnMessage = "无法创建Excel对象,可能您的计算机未安装Excel";
             return false;
         }

         Excel.Workbooks workbooks=xlApp.Workbooks;
         Excel.Workbook workbook=workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
         Excel.Worksheet worksheet=(Excel.Worksheet)workbook.Worksheets[1];//取得sheet1
         worksheet.Cells.Font.Size = 10;
         Excel.Range range;

         long totalCount=dt.Rows.Count;
         long rowRead=0;
         float percent=0;

         worksheet.Cells[1,1]=reportName;
         ((Excel.Range)worksheet.Cells[1,1]).Font.Size = 12;
         ((Excel.Range)worksheet.Cells[1,1]).Font.Bold = true;

         //写入字段
         for(int i=0;i<dt.Columns.Count;i++)
         {
             worksheet.Cells[2,i+1]=dt.Columns[i].ColumnName;
             range=(Excel.Range)worksheet.Cells[2,i+1];
             range.Interior.ColorIndex = 15;
             range.Font.Bold = true;

         }
         //写入数值
         for(int r=0;r<dt.Rows.Count;r++)
         {
             for(int i=0;i<dt.Columns.Count;i++)
             {
                 worksheet.Cells[r+3,i+1]=dt.Rows[r][i].ToString();
             }
             rowRead++;
             percent=((float)(100*rowRead))/totalCount;
         }

         range=worksheet.get_Range(worksheet.Cells[2,1],worksheet.Cells[dt.Rows.Count+2,dt.Columns.Count]);
         range.BorderAround(Excel.XlLineStyle.xlContinuous,Excel.XlBorderWeight.xlThin,Excel.XlColorIndex.xlColorIndexAutomatic,null);
         if( dt.Rows.Count > 0)
         {
             range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].ColorIndex = Excel.XlColorIndex.xlColorIndexAutomatic;
             range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].LineStyle =Excel.XlLineStyle.xlContinuous;
             range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].Weight =Excel.XlBorderWeight.xlThin;
         }
         if(dt.Columns.Count>1)
         {
             range.Borders[Excel.XlBordersIndex.xlInsideVertical].ColorIndex =Excel.XlColorIndex.xlColorIndexAutomatic;
             range.Borders[Excel.XlBordersIndex.xlInsideVertical].LineStyle = Excel.XlLineStyle.xlContinuous;
             range.Borders[Excel.XlBordersIndex.xlInsideVertical].Weight = Excel.XlBorderWeight.xlThin;
         }

         //保存文件
         if(saveFileName!="")
         {
             try
             {
                 workbook.Saved =true;
                 workbook.SaveCopyAs(saveFileName);
                 fileSaved=true;
             }
             catch(Exception ex)
             {
                 fileSaved=false;
                 _ReturnStatus = -1;
                 _ReturnMessage = "导出文件时出错,文件可能正被打开!\n"+ex.Message;
             }
         }
         else
         {
             fileSaved=false;
         }           

         //释放Excel对应的对象
         if(range != null)
         {
             System.Runtime.InteropServices.Marshal.ReleaseComObject(range);
             range = null;
         }
         if(worksheet != null)
         {
             System.Runtime.InteropServices.Marshal.ReleaseComObject(worksheet);
             worksheet = null;
         }
         if(workbook != null)
         {
             System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
             workbook = null;
         }
         if(workbooks != null)
         {
             System.Runtime.InteropServices.Marshal.ReleaseComObject(workbooks);
             workbooks = null;
         }
         xlApp.Application.Workbooks.Close();
         xlApp.Quit();
         if(xlApp != null)
         {
             System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
             xlApp = null;
         }
         GC.Collect();
         return fileSaved;
     }
}
//该代码片段来自于: http://www.sharejs.com/codes/csharp/7261

C#导入导出数据到Excel的通用类代码的更多相关文章

  1. 用EPPlus导入导出数据到excel

    项目上中要用到将数据库中所有表导出为Excel,以及将Excel数据导入数据库中的操作,使用EPPlus组件,编写以下两个函数. using OfficeOpenXml;using OfficeOpe ...

  2. C#自定义导出数据到Excel中的类封装

    using System; using System.IO; using System.Data; using System.Collections; using System.Data.OleDb; ...

  3. C#导出数据到Excel通用的方法类

    导出数据到Excel通用的方法类,请应对需求自行修改. 资源下载列表 using System.Data; using System.IO; namespace IM.Common.Tools { p ...

  4. 一个方便且通用的导出数据到 Excel 的类库

    一个方便且通用的导出数据到 Excel 的类库 起源: 之前在做一个项目时,客户提出了许多的导出数据的需求: 导出用户信息 导出业务实体信息 各种查询都要能导出 导出的数据要和界面上看到的一致 可以分 ...

  5. 使用Open xml 操作Excel系列之二--从data table导出数据到Excel

    由于Excel中提供了透视表PivotTable,许多项目都使用它来作为数据分析报表. 在有些情况下,我们需要在Excel中设计好模板,包括数据源表,透视表等, 当数据导入到数据源表时,自动更新透视表 ...

  6. Dynamics CRM导出数据到Excel

    原创地址:http://www.cnblogs.com/jfzhu/p/4276212.html 转载请注明出处 Pivot Table是微软BI的一个重要工具,所以这里讲一下Dynamics CRM ...

  7. MVC导出数据到EXCEL新方法:将视图或分部视图转换为HTML后再直接返回FileResult

    导出EXCEL方法总结 MVC导出数据到EXCEL的方法有很多种,常见的是: 1.采用EXCEL COM组件来动态生成XLS文件并保存到服务器上,然后转到该文件存放路径即可: 优点:可设置丰富的EXC ...

  8. 利用PHPExcel读取Excel的数据和导出数据到Excel

    PHPExcel是一个PHP类库,用来帮助我们简单.高效实现从Excel读取Excel的数据和导出数据到Excel.也是我们日常开发中,经常会遇到的使用场景.比如有个客户信息表,要批量导出发给同事,我 ...

  9. mysql命令行的导入导出sql,txt,excel(都在linux或windows命令行操作)(转自筑梦悠然)

    原文链接https://blog.csdn.net/wuhuagu_wuhuaguo/article/details/73805962 Mysql导入导出sql,txt,excel 首先我们通过命令行 ...

随机推荐

  1. Python基础:1.数据类型(列表)

    提示:python版本为2.7,windows系统 1.列表(List) List,是一个有序的集合,可以添加.删除其中的元素. >>> colors = ['red', 'oran ...

  2. We~ˇsay~~ˇ

    拂弹每一个音符 与心相印 行走每一段风景 和路缠绵 花开的声音 只能用心倾听 无论曾经如何艰难 我依然在最初的起点 默念歌唱 等你 携手

  3. win7 Sendto修改

    sendto目录现在被移到了这里 %APPDATA%\Microsoft\Windows\SendTo %APPDATA%是个环境变量,具体来说是在这里: C:\users\<username& ...

  4. SSRS集成至Web

    分几步进行,第一步要实现:IReportServerCredentials 接口第二步:拖入ReportViewer控件第三步:进行报表传参控制.具体如下图描述....代码部分参考下附件 using ...

  5. 关于sharepoint 2010无法显示用户中文名的解决方法和详细剖析

    相信这个问题许多做sharepoint的朋友都曾经遇到过,就是本来很正常的中文用户名莫名其妙的变成了“域名\账号”,我本人也遇到过好多次,每次都是百度谷歌一下草草解决问题,始终也没真正去弄明白是怎么回 ...

  6. 多个DIV让float:left属性,最后一个DIV填满剩余的部分

    <DIV style="border:1px solid red; overflow:hidden;zoom:1;">      <DIV style='floa ...

  7. JAXB - Unmarshalling

    A simple approach for unmarshalling an XML document consists of the creation of a JAXB context and t ...

  8. Java 简单算法--打印乘法口诀(只使用一次循环)

    package cn.magicdu.algorithm; /** * 九九乘法口诀表 * * @author xiaoduc * */ public class NineNineMulitTable ...

  9. 重大发现Android studio 如何简单快速修改package name

    好多人都发现Android studio修改包名比较麻烦,只能一级一级的修改,今天偶尔发现了一个快捷方法. 废话不多说: 1 打开项目的AndroidManifest.xml文件 2 鼠标光笔定位到你 ...

  10. NPOI操作EXCEL 类代码

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using NPOI.SS. ...