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 首先我们通过命令行 ...
随机推荐
- Elasticsearch template(待续...)
动态模板 Dynamic templates allow you to define custom mappings that can be applied to dynamically added ...
- MSP430常见问题之工作模式和功耗类
Q1:1,MSP430进入LP 模式后,CPU 停止运行,那么,进入中断执行退出后,由于SR的恢复,导致还处于LP 模式,是否意味着,CPU 在退出中断后立即停止了呢?2,也就是说,进入LP 模式后, ...
- always block內省略else所代表的電路
真 OO无双 之 真乱舞书 寫程式是很快樂的一件事 Since Sep.15,2006 (筆記) always block內省略else所代表的電路 (SOC) (Verilog) Abstract在 ...
- Cordova+angularjs+ionic+vs2015开发(四)
欢迎加群学习:457351423 这里有4000多部学习视频,涵盖各种技术,有需要的欢迎进群学习! 一.布局 Ionic模板提供了一个侧边栏菜单示例项目和标签选项卡示例项目.本案例将两个布局进行结合, ...
- Apache 流媒体 拖动模块编译
Windows使用apxs独立编译 Apache 模块 http://blog.sina.com.cn/s/blog_43b83d340100mdhl.html 安装 apxs 1.解压apxs.zi ...
- jQuery 源码分析5: jQuery 基本静态方法(一)
jQuery在初始化过程中会为自己扩展一些基本的静态方法和属性,以下是jQuery 1.11.3版本 239 ~ 564行间所扩展的静态属性和方法 jQuery.extend({ // 为每个jQ ...
- 10_控制线程_线程让步yield
[线程让步yield()方法] yield()方法可以让当前正在执行的线程暂停,但它不会阻塞该线程,它只是将该线程从运行状态转入就绪状态. 只是让当前的线程暂停一下,让系统的线程调度器重新调度一次. ...
- 关于“undefined reference to”错误
哪些问题可能产生undefined reference to错误? 1.没用生成目标文件 比如说hello.o文件,由于名字写错.路径不对.Makefile缺少. 2.没用添加相应的库文件.so/dl ...
- C++重写与重载、重定义
文章引用自:http://blog.163.com/clevertanglei900@126/blog/static/111352259201102441934870/ 重载overload:是函数名 ...
- Registry uninstall values
Original link: http://windowssucks.wordpress.com/win-registry-uninstall-values/ -------------------- ...