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 首先我们通过命令行 ...
随机推荐
- java基础学习总结二(标识符、字符集、数据类型以及类型转换)
一:标识符 1:标识符可以由字母.数字.下划线_.$符等组成2:标识符的首字母只能是字母.数字.下划线3:标识符不能使用关键字或者保留字4:标识符可以是中文,但是不建议使用中文5:标识符可以任意长,没 ...
- 【itclx面向对象二】窥探itcl面向编程源码
从上一篇博客看出,itcl的语法其实不难,但是有个缺点,编程习惯与当前类似C++常见的面向编程还是有些区别,并且在大型项目实施中这种方式很费劲. 于是有了itclx. 例如: 1.成员变量.成员方法调 ...
- selendroid项目实战2--ruby下的TOAST定位
网上很多 python/java捕获toast的方法,但ruby的简直没见过. selendroid客户端是基于selenium,而不一定需要appium,所以很多selenium的方法可以直接使用, ...
- jquery easyui combobox 级联及触发事件,combobox级联
jquery easyui combobox 级联及触发事件,combobox级联 >>>>>>>>>>>>>>&g ...
- dos下循环复制一张图片的bat
@echo off setlocal enabledelayedexpansion ,,) do ( @echo !dm! copy .png !dm!.png ) 我期待的结果是将140041.pn ...
- monkeyrunner工具同Monkey工具的差别
Monkey: Monkey工具直接运行在设备或模拟器的adb shell中,生成用户或系统的伪随机事件流. monkeyrunner: monkeyrunner工具则是在工作站上通过API定义的特定 ...
- ASP过滤HTML标签
<% Function RemoveHTML(strHTML) Dim objRegExp, Match, Matches Set objRegExp = New Regexp objRegEx ...
- Android开发之闹钟
闹钟开发: 1.需要时间选择器TimePicker 2.需要Calendar类对日期时间进行操作 3.需要AlarmManager//闹钟管理实质是一个全局定时器, 是Android中常用的一种系统级 ...
- [LaTex]Visio文件转EPS文件[转]
在LaTeX系统中,由于DVI 文件经常被转为PostScript 文件,所以LATEX 支持最好的是EPS 格式(Encapsulated Post-Script ,是PostScript 语言的子 ...
- JDBC向oracle插入数据
public static void main(String[] args) throws SQLException { 2 3 4 String driver="oracle.jdbc.d ...