asp.net中導出excel數(shù)據(jù)的方法匯總

字號:


    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)
    {
    //取得數(shù)據(jù)表各列標題,各標題之間以t分割,最后一個列標題后加回車符
    for(i=0;i colheaders+=dt.columns[i].caption.tostring()+t;
    colheaders +=dt.columns[i].caption.tostring() +n;
    //向http輸出流中寫入取得的數(shù)據(jù)信息
    resp.write(colheaders);
    //逐行處理數(shù)據(jù)
    foreach(datarow row in myrow)
    {
    //在當前行中,逐列獲得數(shù)據(jù),數(shù)據(jù)之間以t分割,結(jié)束時加回車符n
    for(i=0;i ls_item +=row[i].tostring() + t;
    ls_item += row[i].tostring() +n;
    //當前行數(shù)據(jù)寫入http輸出流,并且置空ls_item以便下行數(shù)據(jù)
    resp.write(ls_item);
    ls_item=;
    }
    }
    else
    {
    if(typeid==2)
    {
    //從dataset中直接導出xml數(shù)據(jù)并且寫到http輸出流中
    resp.write(ds.getxml());
    }
    }
    //寫緩沖區(qū)中的數(shù)據(jù)到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: 在此處添加構(gòu)造函數(shù)邏輯
    //
    //dv為要輸出到excel的數(shù)據(jù),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;//設置標題格式為居中對齊
    }
    //
    //取得表格中的數(shù)據(jù)
    //
    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;
    // 添加頭信息,為文件下載/另存為對話框指定默認文件名
    response.addheader(content-disposition, attachment; filename= + server.urlencode(file.name));
    // 添加頭信息,指定文件大小,讓瀏覽器能夠顯示下載進度
    response.addheader(content-length, file.length.tostring());
    // 指定返回的是一個不能被客戶端讀取的流,必須被下載
    response.contenttype = application/ms-excel;
    // 把文件流發(fā)送到客戶端
    response.writefile(file.fullname);
    // 停止頁面的執(zhí)行
    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工作簿,需要 設置如下兩行內(nèi)容,以保證工作簿中有一個工作表,
    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];
    //選擇多個連續(xù)的單元格為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);
    //然后現(xiàn)設置合并單元格
    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);
    ⑦、獲取有數(shù)據(jù)的行數(shù)
    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對象的資源與結(jié)束excel 進程
    關于這方面內(nèi)容有好多網(wǎng)友都在講多種方法,經(jīng)過本人實踐,以下方面才能真正做到結(jié)束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、再新建一個方法,并以該方法中執(zhí)行上面新建的操作excel方法,并在執(zhí)行完操作excel方法的后面添加gc.collect():
    //下面方法中outputexcel()方法是輸出excel文件的對excel 操作的方法
    private void killexcel()
    {
    outputexcel();
    gc.collect();
    gc.waitforpendingfinalizers();
    }
    好多網(wǎng)友都在介紹使用gc.collect()釋放excel占用的資源來結(jié)束excel進行,如果將“gc.collect();”與操作excel的業(yè)務寫在一個程序塊中,“gc”是永遠不能結(jié)束excel進程的,在web應用程序中,這種現(xiàn)象是很可怕的事情。原因是gc不會清理本程序塊中的垃圾內(nèi)存的。
    4、在業(yè)務事件中調(diào)用killexcel()方法:
    protected void linkbutton3_click(object sender, eventargs e)
    {
    //導出excel
    killexcel();
    }
    八、一些權(quán)限的基本設置:
    使用以上方法在開發(fā)環(huán)境中調(diào)試程序沒有一點問題,等發(fā)布到服務器上后,程序還是不能正常運行,需要進行如下的權(quán)限設置:
    1、.net導出excel遇到的80070005錯誤的解決方法:
    檢索 com 類工廠中 clsid 為 {00024500-0000-0000-c000-000000000046}的組件時失敗,原因是出現(xiàn)以下錯誤: 80070005基本上.net導出excel文件,都需要如此配置一下,不配置有的時候沒錯,而配置后基本應該不會出錯。
    具體配置方法如下:
    1:在服務器上安裝office的excel軟件.
    2:在開始->運行中輸入dcomcnfg.exe啟動組件服務
    3:依次雙擊組件服務->計算機->我的電腦->dcom配置
    4:在dcom配置中找到microsoft excel 應用程序,在它上面點擊右鍵,然后點擊屬性,彈出microsoft excel 應用程序?qū)傩詫υ捒?BR>    5:點擊標識標簽,選擇交互式用戶
    6:點擊安全標簽,在啟動和激活權(quán)限上點擊自定義,然后點擊對應的編輯按鈕,在彈出的安全性對話框中填加一個network service用戶(注意要選擇本計算機名),并給它賦予本地啟動和本地激活權(quán)限.
    7:依然是安全標簽,在訪問權(quán)限上點擊自定義,然后點擊編輯,在彈出的安全性對話框中也填加一個network service用戶,然后賦予本地訪問權(quán)限.
    8.如果交互式用戶設置后出現(xiàn)錯誤8000401a,可取消交互式用戶,指定為administratr,可暫時解決此問題。進一步的解決方式還有待探討。
    9.采用第8點的設置后,打開excel可能會出現(xiàn)“無法使用對象引用或鏈接”,并且不能進行單元格粘貼。原因不明,取消設置后即可消失。
    以上是本人在近期作開發(fā)時的一點心得,現(xiàn)整理成文檔,供奮戰(zhàn)在程序開發(fā)一線的朋友共享,愿看到的網(wǎng)友能名幫助解決“無法使用對象引用或鏈接”的問題。