C#导入导出数据到Excel的通用类代码
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的通用类代码的更多相关文章
- 用EPPlus导入导出数据到excel
项目上中要用到将数据库中所有表导出为Excel,以及将Excel数据导入数据库中的操作,使用EPPlus组件,编写以下两个函数. using OfficeOpenXml;using OfficeOpe ...
- C#自定义导出数据到Excel中的类封装
using System; using System.IO; using System.Data; using System.Collections; using System.Data.OleDb; ...
- C#导出数据到Excel通用的方法类
导出数据到Excel通用的方法类,请应对需求自行修改. 资源下载列表 using System.Data; using System.IO; namespace IM.Common.Tools { p ...
- 一个方便且通用的导出数据到 Excel 的类库
一个方便且通用的导出数据到 Excel 的类库 起源: 之前在做一个项目时,客户提出了许多的导出数据的需求: 导出用户信息 导出业务实体信息 各种查询都要能导出 导出的数据要和界面上看到的一致 可以分 ...
- 使用Open xml 操作Excel系列之二--从data table导出数据到Excel
由于Excel中提供了透视表PivotTable,许多项目都使用它来作为数据分析报表. 在有些情况下,我们需要在Excel中设计好模板,包括数据源表,透视表等, 当数据导入到数据源表时,自动更新透视表 ...
- Dynamics CRM导出数据到Excel
原创地址:http://www.cnblogs.com/jfzhu/p/4276212.html 转载请注明出处 Pivot Table是微软BI的一个重要工具,所以这里讲一下Dynamics CRM ...
- MVC导出数据到EXCEL新方法:将视图或分部视图转换为HTML后再直接返回FileResult
导出EXCEL方法总结 MVC导出数据到EXCEL的方法有很多种,常见的是: 1.采用EXCEL COM组件来动态生成XLS文件并保存到服务器上,然后转到该文件存放路径即可: 优点:可设置丰富的EXC ...
- 利用PHPExcel读取Excel的数据和导出数据到Excel
PHPExcel是一个PHP类库,用来帮助我们简单.高效实现从Excel读取Excel的数据和导出数据到Excel.也是我们日常开发中,经常会遇到的使用场景.比如有个客户信息表,要批量导出发给同事,我 ...
- mysql命令行的导入导出sql,txt,excel(都在linux或windows命令行操作)(转自筑梦悠然)
原文链接https://blog.csdn.net/wuhuagu_wuhuaguo/article/details/73805962 Mysql导入导出sql,txt,excel 首先我们通过命令行 ...
随机推荐
- C语言——结构体
struct 是一种把一些数据项组合在一起的数据结构.在Go,Rust这些新语言中都保留了结构体 struct 的概念,这是C的精华. 定义匿名结构体 例:学生信息定义为一个结构体,信息内容包括学生的 ...
- [转]Unable to build: the file dx.jar was not loaded from the SDK folder!
本文转自:http://www.developerbits.com/tag/unable-to-build-the-file-dx-jar-was-not-loaded-from-the-sdk-fo ...
- [MSDN]使用 REST 处理文件夹和文件
msdn: http://msdn.microsoft.com/zh-cn/library/dn292553.aspx 了解如何使用 SharePoint 2013 REST 界面对文件夹和文件执行基 ...
- 【高级JEE技术】JMS
ActiveMQ消息服务器. ActiveMQ是apache的一种jms标准实现,支持两种模型,点对点发送消息以及发布订阅者模型. 为了规范JMS API,JMS为消息传送定义了很多概念: JMS客户 ...
- 简单测试IIS下的UrlRewrite技术
UrlRewrite即地址变换.它可以实现静态功能方便搜索引擎收录,比如http://***/news.asp?corangeid=11它可以变为htt://***/news-11.html.这样还实 ...
- 配置WindowsLiveWriter,写cnblogs博客
转载:http://www.haogongju.net/art/2307587 引言 以前写博客一般都是联网在cnblogs上面写,不好的地方就是不联网就写不了,当然我们也可以先记录在word文件,等 ...
- Android入门开发之销毁activity
使用: 销毁.关闭页面activity 如果打开下个页面的同时销毁了本页面,在下个页面无法返回本页面,每次打开APP应用就会先显示一张APP的介绍图.或者LOGO页面,延时几秒进入应用,进入后无法再返 ...
- Android——获取网络图片
布局 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:too ...
- TimesTen ODBC 链接库差异及相关命令行工具的使用注意事项
1. TimesTen有两种访问模式:Direct模式和Client/Server模式,以下为来自Operations Guide 的描述 Connecting using TimesTen ODBC ...
- Cabarc Overview (Microsoft TechNet)
Original Link: Cabarc Overview Applies To: Windows Server 2003, Windows Server 2003 R2, Windows Ser ...