网站首页  汉语字词  英语词汇  考试资料  写作素材  旧版资料

请输入您要查询的考试资料:

 

标题 asp.net中导出excel数据的方法汇总
内容
    1、由dataset生成
    代码如下:
    public void createexcel(dataset ds,string typeid,string filename)
    {
    httpresponse resp;
    resp = page.response;
    resp.contentencoding = system.text.encoding.getencoding(gb2312);
    resp.appendheader(content-disposition, attachment;filename= + filename);
    string colheaders= , ls_item=;
    int i=0;
    //定义表对象与行对像,同时用dataset对其值进行初始化
    datatable dt=ds.tables[0];
    datarow[] myrow=dt.select();
    // typeid==1时导出为excel格式文件;typeid==2时导出为xml格式文件
    if(typeid==1)
    {
    //取得数据表各列标题,各标题之间以t分割,最后一个列标题后加回车符
    for(i=0;i colheaders+=dt.columns[i].caption.tostring()+t;
    colheaders +=dt.columns[i].caption.tostring() +n;
    //向http输出流中写入取得的数据信息
    resp.write(colheaders);
    //逐行处理数据
    foreach(datarow row in myrow)
    {
    //在当前行中,逐列获得数据,数据之间以t分割,结束时加回车符n
    for(i=0;i ls_item +=row[i].tostring() + t;
    ls_item += row[i].tostring() +n;
    //当前行数据写入http输出流,并且置空ls_item以便下行数据
    resp.write(ls_item);
    ls_item=;
    }
    }
    else
    {
    if(typeid==2)
    {
    //从dataset中直接导出xml数据并且写到http输出流中
    resp.write(ds.getxml());
    }
    }
    //写缓冲区中的数据到http头文件中
    resp.end();
    }
    2、由datagrid生成
    代码如下:
    public void toexcel(system.web.ui.control ctl)
    {
    httpcontext.current.response.appendheader(content-disposition,attachment;filename=excel.xls);
    httpcontext.current.response.charset =utf-8;
    httpcontext.current.response.contentencoding =system.text.encoding.default;
    httpcontext.current.response.contenttype =application/ms-excel;//image/jpeg;text/html;image/gif;vnd.ms-excel/msword
    ctl.page.enableviewstate =false;
    system.io.stringwriter tw = new system.io.stringwriter() ;
    system.web.ui.htmltextwriter hw = new system.web.ui.htmltextwriter (tw);
    ctl.rendercontrol(hw);
    httpcontext.current.response.write(tw.tostring());
    httpcontext.current.response.end();
    }
    用法:toexcel(datagrid1);
    3、这个用dataview
    代码如下:
    public void outputexcel(dataview dv,string str)
    {
    //
    // todo: 在此处添加构造函数逻辑
    //
    //dv为要输出到excel的数据,str为标题名称
    gc.collect();
    application excel;// = new application();
    int rowindex=4;
    int colindex=1;
    _workbook xbk;
    _worksheet xst;
    excel= new applicationclass();
    xbk = excel.workbooks.add(true);
    xst = (_worksheet)xbk.activesheet;
    //
    //取得标题
    //
    foreach(datacolumn col in dv.table.columns)
    {
    colindex++;
    excel.cells[4,colindex] = col.columnname;
    xst.get_range(excel.cells[4,colindex],excel.cells[4,colindex]).horizontalalignment = xlvalign.xlvaligncenter;//设置标题格式为居中对齐
    }
    //
    //取得表格中的数据
    //
    foreach(datarowview row in dv)
    {
    rowindex ++;
    colindex = 1;
    foreach(datacolumn col in dv.table.columns)
    {
    colindex ++;
    if(col.datatype == system.type.gettype(system.datetime))
    {
    excel.cells[rowindex,colindex] = (convert.todatetime(row[col.columnname].tostring())).tostring(yyyy-mm-dd);
    xst.get_range(excel.cells[rowindex,colindex],excel.cells[rowindex,colindex]).horizontalalignment = xlvalign.xlvaligncenter;//设置日期型的字段格式为居中对齐
    }
    else
    if(col.datatype == system.type.gettype(system.string))
    {
    excel.cells[rowindex,colindex] = '+row[col.columnname].tostring();
    xst.get_range(excel.cells[rowindex,colindex],excel.cells[rowindex,colindex]).horizontalalignment = xlvalign.xlvaligncenter;//设置字符型的字段格式为居中对齐
    }
    else
    {
    excel.cells[rowindex,colindex] = row[col.columnname].tostring();
    }
    }
    }
    //
    //加载一个合计行
    //
    int rowsum = rowindex + 1;
    int colsum = 2;
    excel.cells[rowsum,2] = 合计;
    xst.get_range(excel.cells[rowsum,2],excel.cells[rowsum,2]).horizontalalignment = xlhalign.xlhaligncenter;
    //
    //设置选中的部分的颜色
    //
    xst.get_range(excel.cells[rowsum,colsum],excel.cells[rowsum,colindex]).select();
    xst.get_range(excel.cells[rowsum,colsum],excel.cells[rowsum,colindex]).interior.colorindex = 19;//设置为浅黄色,共计有56种
    //
    //取得整个报表的标题
    //
    excel.cells[2,2] = str;
    //
    //设置整个报表的标题格式
    //
    xst.get_range(excel.cells[2,2],excel.cells[2,2]).font.bold = true;
    xst.get_range(excel.cells[2,2],excel.cells[2,2]).font.size = 22;
    //
    //设置报表表格为最适应宽度
    //
    xst.get_range(excel.cells[4,2],excel.cells[rowsum,colindex]).select();
    xst.get_range(excel.cells[4,2],excel.cells[rowsum,colindex]).columns.autofit();
    //
    //设置整个报表的标题为跨列居中
    //
    xst.get_range(excel.cells[2,2],excel.cells[2,colindex]).select();
    xst.get_range(excel.cells[2,2],excel.cells[2,colindex]).horizontalalignment = xlhalign.xlhaligncenteracrossselection;
    //
    //绘制边框
    //
    xst.get_range(excel.cells[4,2],excel.cells[rowsum,colindex]).borders.linestyle = 1;
    xst.get_range(excel.cells[4,2],excel.cells[rowsum,2]).borders[xlbordersindex.xledgeleft].weight = xlborderweight.xlthick;//设置左边线加粗
    xst.get_range(excel.cells[4,2],excel.cells[4,colindex]).borders[xlbordersindex.xledgetop].weight = xlborderweight.xlthick;//设置上边线加粗
    xst.get_range(excel.cells[4,colindex],excel.cells[rowsum,colindex]).borders[xlbordersindex.xledgeright].weight = xlborderweight.xlthick;//设置右边线加粗
    xst.get_range(excel.cells[rowsum,2],excel.cells[rowsum,colindex]).borders[xlbordersindex.xledgebottom].weight = xlborderweight.xlthick;//设置下边线加粗
    //
    //显示效果
    //
    excel.visible=true;
    //xst.export(server.mappath(.)++this.xlfile.text+.xls,
    sheetexportactionenum.ssexportactionnone,microsoft.office.interop.owc.sheetexportformat.ssexporthtml);
    xbk.savecopyas(server.mappath(.)++this.xlfile.text+.xls);
    ds = null;
    xbk.close(false, null,null);
    excel.quit();
    system.runtime.interopservices.marshal.releasecomobject(xbk);
    system.runtime.interopservices.marshal.releasecomobject(excel);
    system.runtime.interopservices.marshal.releasecomobject(xst);
    xbk = null;
    excel = null;
    xst = null;
    gc.collect();
    string path = server.mappath(this.xlfile.text+.xls);
    system.io.fileinfo file = new system.io.fileinfo(path);
    response.clear();
    response.charset=gb2312;
    response.contentencoding=system.text.encoding.utf8;
    // 添加头信息,http://www.111cn.net为文件下载/另存为对话框指定默认文件名
    response.addheader(content-disposition, attachment; filename= + server.urlencode(file.name));
    // 添加头信息,指定文件大小,让浏览器能够显示下载进度
    response.addheader(content-length, file.length.tostring());
    // 指定返回的是一个不能被客户端读取的流,必须被下载
    response.contenttype = application/ms-excel;
    // 把文件流发送到客户端
    response.writefile(file.fullname);
    // 停止页面的执行
    response.end();
    }
    导入、导出excel中的一些问题汇总
    一、在项目中的添加引用:
    右击项目资源管理器的引用-->添加引用-->选择.net选项卡-->选择microsoft.office.interop.excel-->确定(如下图);
    在选择时注意一下.net组件的版本号,图是的12.0.0.0是office2007的版本:
    二、在项目中使用microsoft.office.interop.excel:
    如果想使用microsoft.office.interop.excel,首先需要在项目中引用命名空间:
    using microsoft.office.interop.excel;
    三、建立excel.application相关对象
    //建立application对象
    microsoft.office.interop.excel.application myexcel = new application();
    //建立workbooks对象
    workbooks mybooks = myexcel.application.workbooks;
    //建立一个system.reflection.missing的object对象
    object omissing = system.reflection.missing.value;
    四、打开或新建excel的book文件
    //打开excel文件,注意里的“exccelfilepath”为excel文件在服务器上的物理地址,包括文件名
    workbook mybook = mybooks.open(exccelfilepath,omissing, omissing, omissing, omissing, omissing, omissing, omissing, omissing, omissing, omissing, omissing, omissing);
    //新建workseet对象,,此处为要操作的工作表 ,当前要操作的工作表的获取方法有两种:使用工作表的索引值或使用工作表的名称,名称默认为:“sheet1”/“sheet2”等
    worksheet mysheet = (worksheet)mybook.worksheets[1];
    //如果是新建excel工作簿,需要 设置如下两行内容,以保证工作簿中有一个工作表,
    workbook workbook1 = excel1.workbooks.add(true);
    worksheet mysheet= (worksheet)workbook1.worksheets[sheet1];
    //设置excel对象是否显示界面,默认为false不显示界面
    myexcel.visble=true;
    五、一些比较重要的针对excel的操作
    1、获取range对象
    ①、获取一个单元格的range对象:
    //选择第一行、第一列的单元的单元格为range对象
    range r = (excel.range)mysheet.cells[1, 1];
    //选择多个连续的单元格为range对象
    range r=(excel.range)range.get_range(a1:f3)
    ②、给单元格赋值或取出单元格的值:
    //已选择了range对象的赋值:
    r.text=中国;
    //未选择range对象的赋值:
    mysheet.cells[1,2].text=中国;
    //已选择了range对象的取值:
    string strvalue= r.text;
    //未选择range对象的取值:
    string strvalue= mysheet.cells[1,2].text;
    ③、给单元格设置边框
    mysheet.cells[2, 1].borderaround(xllinestyle.xlcontinuous, xlborderweight.xlthin, xlcolorindex.xlcolorindexautomatic, null);//画线
    ④、合并单元格
    //合并单元格前先要将要合并的单元格选择为range对象
    range r=range.get_range(a1:f3);
    //然后现设置合并单元格
    r.mergecells = true;
    ⑤、设置单元格的字体、字号、背景色等属性
    mysheet.cells[1, 1].font.name = 黑体;
    mysheet.cells[1, 1].font.size = 20;
    mysheet.rows[1:1].rowheight = 40;
    mysheet.cells[1, 1].interior.color = color.fromargb(224, 224, 224);//设置颜色
    ⑥、删除一行:
    //首先获取要删除的行的range
    microsoft.office.interop.excel.range range = (microsoft.office.interop.excel.range)mysheet.rows[sendedrow[1], type.missing];
    //注意删除行后删除后的行号被下面的行替换,如果逐行删除,请先从最大的行号往最小的行号删除
    range.delete(microsoft.office.interop.excel.xldeleteshiftdirection.xlshiftup);
    ⑦、获取有数据的行数
    int rowsint = mysheet.usedrange.cells.rows.count;
    六、excel文件的保存与退出
    1、excel的保存与退出
    mybook.save();
    mybooks.close();
    myexcel.quit();
    2、excel指定文件保存
    mybook.close(true, filepath +_file_name, null);
    七、释放excle对象的资源与结束excel 进程
    关于这方面内容有好多网友都在讲多种方法,经过本人实践,以下方面才能真正做到结束excel的任务进程:
    1、将所有以上对excel的操作放到一个方法中,
    2、在操作excel后,即时将不使用对象一一释放并赋null值:
    system.runtime.interopservices.marshal.releasecomobject(mysheet);
    mysheet=null;
    system.runtime.interopservices.marshal.releasecomobject(mybook);
    mybook=null;//http://www.111cn.net
    system.runtime.interopservices.marshal.releasecomobject(mybooks);
    mybooks=null;
    system.runtime.interopservices.marshal.releasecomobject(myexcel);
    myexcel=null;
    3、再新建一个方法,并以该方法中执行上面新建的操作excel方法,并在执行完操作excel方法的后面添加gc.collect():
    //下面方法中outputexcel()方法是输出excel文件的对excel 操作的方法
    private void killexcel()
    {
    outputexcel();
    gc.collect();
    gc.waitforpendingfinalizers();
    }
    好多网友都在介绍使用gc.collect()释放excel占用的资源来结束excel进行,如果将“gc.collect();”与操作excel的业务写在一个程序块中,“gc”是永远不能结束excel进程的,在web应用程序中,这种现象是很可怕的事情。原因是gc不会清理本程序块中的垃圾内存的。
    4、在业务事件中调用killexcel()方法:
    protected void linkbutton3_click(object sender, eventargs e)
    {
    //导出excel
    killexcel();
    }
    八、一些权限的基本设置:
    使用以上方法在开发环境中调试程序没有一点问题,等发布到服务器上后,程序还是不能正常运行,需要进行如下的权限设置:
    1、.net导出excel遇到的80070005错误的解决方法:
    检索 com 类工厂中 clsid 为 {00024500-0000-0000-c000-000000000046}的组件时失败,原因是出现以下错误: 80070005基本上.net导出excel文件,都需要如此配置一下,不配置有的时候没错,而配置后基本应该不会出错。
    具体配置方法如下:
    1:在服务器上安装office的excel软件.
    2:在开始->运行中输入dcomcnfg.exe启动组件服务
    3:依次双击组件服务->计算机->我的电脑->dcom配置
    4:在dcom配置中找到microsoft excel 应用程序,在它上面点击右键,然后点击属性,弹出microsoft excel 应用程序属性对话框
    5:点击标识标签,选择交互式用户
    6:点击安全标签,在启动和激活权限上点击自定义,然后点击对应的编辑按钮,在弹出的安全性对话框中填加一个network service用户(注意要选择本计算机名),并给它赋予本地启动和本地激活权限.
    7:依然是安全标签,在访问权限上点击自定义,然后点击编辑,在弹出的安全性对话框中也填加一个network service用户,然后赋予本地访问权限.
    8.如果交互式用户设置后出现错误8000401a,可取消交互式用户,指定为administratr,可暂时解决此问题。进一步的解决方式还有待探讨。
    9.采用第8点的设置后,打开excel可能会出现“无法使用对象引用或链接”,并且不能进行单元格粘贴。原因不明,取消设置后即可消失。
    以上是本人在近期作开发时的一点心得,现整理成文档,供奋战在程序开发一线的朋友共享,愿看到的网友能名帮助解决“无法使用对象引用或链接”的问题。
随便看

 

在线学习网考试资料包含高考、自考、专升本考试、人事考试、公务员考试、大学生村官考试、特岗教师招聘考试、事业单位招聘考试、企业人才招聘、银行招聘、教师招聘、农村信用社招聘、各类资格证书考试等各类考试资料。

 

Copyright © 2002-2024 cuapp.net All Rights Reserved
更新时间:2025/5/21 3:12:40