本文先描述如何用c#连接、操作excel文件。

项目中需要引入的DLL文件为Interop.Excel、Interop.Microsoft.Office.Core、Interop.Office等。

操作excel前需要定义一些excel变量:

定义操作excel的公共变量[www.cn-web.com]

public Excel.Application m_objExcel = null;//Excel的工作环境

public Excel._Workbook m_objBook = null;//工作簿对象

public Excel.Sheets m_objsheets = null;//工作表集合

public Excel._Worksheet m_objSheet = null;//活动工作表

public Excel.Range m_objRange = null;//选择单元格

连接excel文件并选择要操作的表[www.cn-web.com]

string excelfilename="cn-web-com/1.xls";

excelfilename=Server.MapPath(excelfilename);//取得excel文件的地址

m_objExcel = new Excel.Application();

m_objBook = m_objExcel.Workbooks.Open(excelfilename, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt);

m_objsheets=m_objBook.Worksheets;

m_objSheet=(_Worksheet)m_objsheets.get_Item(1);//选择的是第一个表

经过以上操作,我们可以连接上了excel并获取excel里第一张表的对象:m_objSheet。

连接上后,我们向excel表里写入数据:

向excel某单元格内写入数据[www.cn-web.com]

string pos="A1";//excel中A1的位置。

m_objRange = m_objSheet.get_Range(_pos, m_objOpt);//取得单元格

m_objRange.Value2 = "技术支持:cn-web.com(老韩)";//向A1单元格中写入数据

接着,我们将此excel另存:

保存excel文档[www.cn-web.com]

m_objBook.SaveAs(savefileurl, oP.m_objOpt, oP.m_objOpt, oP.m_objOpt, oP.m_objOpt, oP.m_objOpt, Excel.XlSaveAsAccessMode.xlShared, oP.m_objOpt, oP.m_objOpt, oP.m_objOpt, oP.m_objOpt);//savefileurl为物理地址

最后,要记着关闭excel进程:

关闭excel操作进程[www.cn-web.com]

m_objBook.Close(m_objOpt, m_objOpt, m_objOpt);

m_objExcel.Workbooks.Close();

m_objExcel.Quit();

System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objBook);

System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objExcel);

m_objBook = null;

m_objExcel = null;

GC.Collect();

foreach (System.Diagnostics.Process p in System.Diagnostics.Process.GetProcesses())

{

if (p.ProcessName.ToUpper() == "EXCEL")

{

p.Kill();

}

}

Asp.Net下导出/导入规则的Excel(.xls)文件

datatable中的数据导出excel文件

/// <summary>

/// 将datatable中的数据导出到指定的excel文件中

/// </summary>

/// <param name="page">web页面对象</param>

/// <param name="tab">包含被导出数据的datatable对象</param>

/// <param name="filename">excel文件的名称</param>

public static void export(system.web.ui.page page,system.data.datatable tab,string filename)

{

system.web.httpresponse httpresponse = page.response;

system.web.ui.webcontrols.datagrid datagrid=new system.web.ui.webcontrols.datagrid();

datagrid.datasource=tab.defaultview;

datagrid.allowpaging = false;

datagrid.headerstyle.backcolor = system.drawing.color.green;

datagrid.headerstyle.horizontalalign = horizontalalign.center;

datagrid.headerstyle.font.bold = true;

datagrid.databind();

httpresponse.appendheader("content-disposition","attachment;filename="+httputility.urlencode(filename,system.text.encoding.utf8)); //filename="*.xls";

httpresponse.contentencoding=system.text.encoding.getencoding("gb2312");

httpresponse.contenttype ="application/ms-excel";

system.io.stringwriter tw = new system.io.stringwriter() ;

system.web.ui.htmltextwriter hw = new system.web.ui.htmltextwriter (tw);

datagrid.rendercontrol(hw);

string filepath = page.server.mappath("..")+"\\files\\" +filename;

system.io.streamwriter sw = system.io.file.createtext(filepath);

sw.write(tw.tostring());

sw.close();

downfile(httpresponse,filename,filepath);

httpresponse.end();

}

private static bool downfile(system.web.httpresponse response,string filename,string fullpath)

{

try

{

response.contenttype = "application/octet-stream";

response.appendheader("content-disposition","attachment;filename=" +

httputility.urlencode(filename,system.text.encoding.utf8) + ";charset=gb2312");

system.io.filestream fs= system.io.file.openread(fullpath);

long flen=fs.length;

int size=102400;//每100k同时下载数据

byte[] readdata = new byte[size];//指定缓冲区的大小

if(size>flen)size=convert.toint32(flen);

long fpos=0;

bool isend=false;

while (!isend)

{

if((fpos+size)>flen)

{

size=convert.toint32(flen-fpos);

readdata = new byte[size];

isend=true;

}

fs.read(readdata, 0, size);//读入一个压缩块

response.binarywrite(readdata);

fpos+=size;

}

fs.close();

system.io.file.delete(fullpath);

return true;

}

catch

{

return false;

}

}

将指定excel文件中的数据转换成datatable

/// <summary>

/// 将指定excel文件中的数据转换成datatable对象,供应用程序进一步处理

/// </summary>

/// <param name="filepath"></param>

/// <returns></returns>

public static system.data.datatable import(string filepath)

{

system.data.datatable rs = new system.data.datatable();

bool canopen=false;

oledbconnection conn = new oledbconnection("provider=microsoft.jet.oledb.4.0;"+

"data source=" + filepath + ";" +

"extended properties=\"excel 8.0;\"");

try//尝试数据连接是否可用

{

conn.open();

conn.close();

canopen=true;

}

catch{}

if(canopen)

{

try//如果数据连接可以打开则尝试读入数据

{

oledbcommand myoledbcommand = new oledbcommand("select * from [sheet1$]",conn);

oledbdataadapter mydata = new oledbdataadapter(myoledbcommand);

mydata.fill(rs);

conn.close();

}

catch//如果数据连接可以打开但是读入数据失败,则从文件中提取出工作表的名称,再读入数据

{

string sheetname=getsheetname(filepath);

if(sheetname.length>0)

{

oledbcommand myoledbcommand = new oledbcommand("select * from ["+sheetname+"$]",conn);

oledbdataadapter mydata = new oledbdataadapter(myoledbcommand);

mydata.fill(rs);

conn.close();

}

}

}

else

{

system.io.streamreader tmpstream=file.opentext(filepath);

string tmpstr=tmpstream.readtoend();

tmpstream.close();

rs=getdatatablefromstring(tmpstr);

tmpstr="";

}

return rs;

}

/// <summary>

/// 将指定html字符串的数据转换成datatable对象 --根据“<tr><td>”等特殊字符进行处理

/// </summary>

/// <param name="tmphtml">html字符串</param>

/// <returns></returns>

private static datatable getdatatablefromstring(string tmphtml)

{

string tmpstr=tmphtml;

datatable tb=new datatable();

//先处理一下这个字符串,删除第一个<tr>之前合最后一个</tr>之后的部分

int index=tmpstr.indexof("<tr");

if(index>-1)

tmpstr=tmpstr.substring(index);

else

return tb;

index=tmpstr.lastindexof("</tr>");

if(index>-1)

tmpstr=tmpstr.substring(0,index+5);

else

return tb;

bool existssparator=false;

char separator=convert.tochar("^");

//如果原字符串中包含分隔符“^”则先把它替换掉

if(tmpstr.indexof(separator.tostring())>-1)

{

existssparator=true;

tmpstr=tmpstr.replace("^","^$&^");

}

//先根据“</tr>”分拆

string[] tmprow=tmpstr.replace("</tr>","^").split(separator);

for(int i=0;i<tmprow.length-1;i++)

{

datarow newrow=tb.newrow();

string tmpstri=tmprow[i];

if(tmpstri.indexof("<tr")>-1)

{

tmpstri=tmpstri.substring(tmpstri.indexof("<tr"));

if(tmpstri.indexof("display:none")<0||tmpstri.indexof("display:none")>tmpstri.indexof(">"))

{

tmpstri=tmpstri.replace("</td>","^");

string[] tmpfield=tmpstri.split(separator);

for(int j=0;j<tmpfield.length-1;j++)

{

tmpfield[j]=removestring(tmpfield[j],"<font>");

index=tmpfield[j].lastindexof(">")+1;

if(index>0)

{

string field=tmpfield[j].substring(index,tmpfield[j].length-index);

if(existssparator) field=field.replace("^$&^","^");

if(i==0)

{

string tmpfieldname=field;

int sn=1;

while(tb.columns.contains(tmpfieldname))

{

tmpfieldname=field+sn.tostring();

sn+=1;

}

tb.columns.add(tmpfieldname);

}

else

{

newrow[j]=field;

}

}//end of if(index>0)

}

if(i>0)

tb.rows.add(newrow);

}

}

}

tb.acceptchanges();

return tb;

}

/// <summary>

/// 从指定html字符串中剔除指定的对象

/// </summary>

/// <param name="tmphtml">html字符串</param>

/// <param name="remove">需要剔除的对象--例如输入"<font>"则剔除"<font ???????>"和"</font>>"</param>

/// <returns></returns>

public static string removestring(string tmphtml,string remove)

{

tmphtml=tmphtml.replace(remove.replace("<","</"),"");

tmphtml=removestringhead(tmphtml,remove);

return tmphtml;

}

/// <summary>

/// 只供方法removestring()使用

/// </summary>

/// <returns></returns>

private static string removestringhead(string tmphtml,string remove)

{

//为了方便注释,假设输入参数remove="<font>"

if(remove.length<1) return tmphtml;//参数remove为空:不处理返回

if((remove.substring(0,1)!="<")||(remove.substring(remove.length-1)!=">")) return tmphtml;//参数remove不是<?????>:不处理返回

int indexs=tmphtml.indexof(remove.replace(">",""));//查找“<font”的位置

int indexe=-1;

if(indexs>-1)

{

string tmpright=tmphtml.substring(indexs,tmphtml.length-indexs);

indexe=tmpright.indexof(">");

if(indexe>-1)

tmphtml=tmphtml.substring(0,indexs)+tmphtml.substring(indexs+indexe+1);

if(tmphtml.indexof(remove.replace(">",""))>-1)

tmphtml=removestringhead(tmphtml,remove);

}

return tmphtml;

}

/// <summary>

/// 将指定excel文件中读取第一张工作表的名称

/// </summary>

/// <param name="filepath"></param>

/// <returns></returns>

private static string getsheetname(string filepath)

{

string sheetname="";

system.io.filestream tmpstream=file.openread(filepath);

byte[] filebyte=new byte[tmpstream.length];

tmpstream.read(filebyte,0,filebyte.length);

tmpstream.close();

byte[] tmpbyte=new byte[]{convert.tobyte(11),convert.tobyte(0),convert.tobyte(0),convert.tobyte(0),convert.tobyte(0),convert.tobyte(0),convert.tobyte(0),convert.tobyte(0),

convert.tobyte(11),convert.tobyte(0),convert.tobyte(0),convert.tobyte(0),convert.tobyte(0),convert.tobyte(0),convert.tobyte(0),convert.tobyte(0),

convert.tobyte(30),convert.tobyte(16),convert.tobyte(0),convert.tobyte(0)};

int index=getsheetindex(filebyte,tmpbyte);

if(index>-1)

{

index+=16+12;

system.collections.arraylist sheetnamelist=new system.collections.arraylist();

for(int i=index;i<filebyte.length-1;i++)

{

byte temp=filebyte[i];

if(temp!=convert.tobyte(0))

sheetnamelist.add(temp);

else

break;

}

byte[] sheetnamebyte=new byte[sheetnamelist.count];

for(int i=0;i<sheetnamelist.count;i++)

sheetnamebyte[i]=convert.tobyte(sheetnamelist[i]);

sheetname=system.text.encoding.default.getstring(sheetnamebyte);

}

return sheetname;

}

/// <summary>

/// 只供方法getsheetname()使用

/// </summary>

/// <returns></returns>

private static int getsheetindex(byte[] findtarget,byte[] finditem)

{

int index=-1;

int finditemlength=finditem.length;

if(finditemlength<1) return -1;

int findtargetlength=findtarget.length;

if((findtargetlength-1)<finditemlength) return -1;

for(int i=findtargetlength-finditemlength-1;i>-1;i--)

{

system.collections.arraylist tmplist=new system.collections.arraylist();

int find=0;

for(int j=0;j<finditemlength;j++)

{

if(findtarget[i+j]==finditem[j]) find+=1;

}

if(find==finditemlength)

{

index=i;

break;

}

}

return index;

}

C#对excel的操作的更多相关文章

  1. VS2010 MFC对Excel的操作

    这是帮别人做项目遇到的一个问题,的那个是纠结了老长时间,本以为是一件很轻松的事... 首先,这里采用了OLE来对Excel进行操作,网上其实有大把的例子,虽然都可以运行,但是并不能满足项目要求,其实我 ...

  2. NPOI对Excel的操作(Sheet转DataTable、List<T>)

    通过NPOI对Excel进行操作,这里主要是读取的操作.封装到ExcelHelper操作类中. 1 using System.Collections.Generic; 2 using NPOI.HSS ...

  3. php的Excel相关操作

    1.需求 把数据库的数据输出excel格式 2.解决方案 利用phpexcel中的examples的01和07,对excel文件的读写 3.操作流程 a.https://github.com/PHPO ...

  4. java导入导出excel常用操作小结及简单示例

    POI中常用设置EXCEL的操作小结: 操作excel如下 HSSFWorkbook wb = new HSSFWorkbook();  //创建一个webbook,对应一个Excel文件 HSSFS ...

  5. C# 几十万级数据导出Excel,及Excel各种操作

    先上导出代码 /// <summary> /// 导出速度最快 /// </summary> /// <param name="list">&l ...

  6. 对Aspose.Cells Excel文件操作的扩展

    工作中对Excel操作的需求很是常见,今天其他项目组的同事在进行Excel数据导入时,使用Aspose.Cells Excel 遇到了些问题. 刚好闲来不忙,回想自己用过的Excel文件操作,有NPO ...

  7. Java学习---Excel读写操作

    1.1.1. 简介 Apache POI 使用Apache POI 完成Excel读写操作 Apache POI 是用Java编写的免费开源的跨平台的 Java API,Apache POI提供API ...

  8. Excel VBA入门(五)Excel对象操作

    本章是本系列教程的重点.但我觉得应该不是难点.从第零章开始到学完本章,应该可以把VBA用于实战中了. Excel对象主要有4个: 工作薄 Workbook 工作表 Worksheet 单元格区域 Ra ...

  9. 网页中NPIO对Excel的操作实例

    上一节是在wpf中实现对excel的操作方法,这一节看看网页中如何封装实现对excel的上传导入和下载保存的. 看看效果图:

  10. vbscript 中对excel常见操作

    vbs 对excel的操作 删除.修改单元格,设置字体.背景色dim oExcel,oWb,oSheet Set oExcel= CreateObject("Excel.Applicatio ...

随机推荐

  1. C#类库帮助类

    前言 此篇专门记录一些常见DB帮助类及其他帮助类,以便使用时不用重复造轮子. DBHelper帮助类 ①首当其冲的就是Sql Server帮助类,创建名为DbHelperSQL 的类 ,全部代码如下: ...

  2. js将用户上传gif动图分解成多张帧图片

    js将用户上传gif动图分解成多张帧图片 写在前面 工作中遇到一个这么一个需求:这是一个多图上传的场景,如果用户上传选择多张图片,则上传后直接展示多张图片,如果上传的图片是gif动图,则需要分解这张动 ...

  3. grub手动引导win7

    grub>rootnoverify (hd0,0)--->win7系统安装盘号 grub > chainloader +1 grub > makeactive     ---& ...

  4. mock调用返回值是void类型

    //调用void方法 doNothing().when(templateWrapper).process();// doCallRealMethod().when(templateWrapper).p ...

  5. 整合Thinkphp数据库基本操作CURD,界面datagrid采用EasyUi的Demo

     1 <?php  2     class CurdAction extends Action{  3         public function del($id){  4          ...

  6. Android Notification使用方法

    1.http://www.cnblogs.com/plokmju/p/android_Notification.html 2.http://blog.csdn.net/vipzjyno1/articl ...

  7. [浪风JQuery开发]jquery最有意思的IFrame类似应用--值得深入研究

    前几天一时兴起答应朋友的需求--做一个外国的企业网站: 本想做就做呗,可没想我辛辛苦苦用浪风认真php平台开发后,对方来一句我服务器不能安装其他程序,请给我用frame框架开发. 浪风那是一个苦字难言 ...

  8. Servlet 发送电子邮件

    使用 Servlet 发送一封电子邮件是很简单的,但首先您必须在您的计算机上安装 JavaMail API 和 Java Activation Framework)JAF). 您可以从 Java 网站 ...

  9. 【ask】vmware(NAT)中的linux突然无法访问互联网网址,但是直接用ip可以访问。

    前两天虚拟机里的linuxmint不知何故,突然无法访问互联网了.依稀记得是升级了win7下面的360安全卫士之后发生的事情.所以, 第1步就开始去找防火墙的各种设置,结果没有查到结果. 第2步猛然看 ...

  10. day7笔记

    一.上节回顾 字典:dic = {'name':'alex'} 1,增 dic['k'] = 'v' 有键值对,则覆盖 setdefault 有键值对,不添加 dic.setdefault('k1', ...