asp.net中導(dǎo)出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;
    //定義表對象與行對像,同時(shí)用DataSet對其值進(jìn)行初始化
    DataTable dt=ds.Tables[0];
    DataRow[] myRow=dt.Select("");
    // typeid=="1"時(shí)導(dǎo)出為EXCEL格式文件;typeid=="2"時(shí)導(dǎo)出為XML格式文件
    if(typeid=="1")
    {
    //取得數(shù)據(jù)表各列標(biāo)題,各標(biāo)題之間以t分割,最后一個(gè)列標(biāo)題后加回車符
    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)
    {
    //在當(dāng)前行中,逐列獲得數(shù)據(jù),數(shù)據(jù)之間以t分割,結(jié)束時(shí)加回車符n
    for(i=0;i ls_item +=row[i].ToString() + "t";
    ls_item += row[i].ToString() +"n";
    //當(dāng)前行數(shù)據(jù)寫入HTTP輸出流,并且置空ls_item以便下行數(shù)據(jù)
    resp.Write(ls_item);
    ls_item="";
    }
    }
    else
    {
    if(typeid=="2")
    {
    //從DataSet中直接導(dǎo)出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、這個(gè)用dataview
    代碼如下:
    public void OutputExcel(DataView dv,string str)
    {
    //
    // TODO: 在此處添加構(gòu)造函數(shù)邏輯
    //
    //dv為要輸出到Excel的數(shù)據(jù),str為標(biāo)題名稱
    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;
    //
    //取得標(biāo)題
    //
    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è)置標(biāo)題格式為居中對齊
    }
    //
    //取得表格中的數(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;//設(shè)置日期型的字段格式為居中對齊
    }
    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;//設(shè)置字符型的字段格式為居中對齊
    }
    else
    {
    excel.Cells[rowIndex,colIndex] = row[col.ColumnName].ToString();
    }
    }
    }
    //
    //加載一個(gè)合計(jì)行
    //
    int rowSum = rowIndex + 1;
    int colSum = 2;
    excel.Cells[rowSum,2] = "合計(jì)";
    xSt.get_Range(excel.Cells[rowSum,2],excel.Cells[rowSum,2]).HorizontalAlignment = XlHAlign.xlHAlignCenter;
    //
    //設(shè)置選中的部分的顏色
    //
    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;//設(shè)置為淺黃色,共計(jì)有56種
    //
    //取得整個(gè)報(bào)表的標(biāo)題
    //
    excel.Cells[2,2] = str;
    //
    //設(shè)置整個(gè)報(bào)表的標(biāo)題格式
    //
    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;
    //
    //設(shè)置報(bào)表表格為最適應(yīng)寬度
    //
    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();
    //
    //設(shè)置整個(gè)報(bào)表的標(biāo)題為跨列居中
    //
    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;//設(shè)置左邊線加粗
    xSt.get_Range(excel.Cells[4,2],excel.Cells[4,colIndex]).Borders[XlBordersIndex.xlEdgeTop].Weight = XlBorderWeight.xlThick;//設(shè)置上邊線加粗
    xSt.get_Range(excel.Cells[4,colIndex],excel.Cells[rowSum,colIndex]).Borders[XlBordersIndex.xlEdgeRight].Weight = XlBorderWeight.xlThick;//設(shè)置右邊線加粗
    xSt.get_Range(excel.Cells[rowSum,2],excel.Cells[rowSum,colIndex]).Borders[XlBordersIndex.xlEdgeBottom].Weight = XlBorderWeight.xlThick;//設(shè)置下邊線加粗
    //
    //顯示效果
    //
    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;
    // 添加頭信息,為"文件下載/另存為"對話框指定默認(rèn)文件名
    Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(file.Name));
    // 添加頭信息,指定文件大小,讓瀏覽器能夠顯示下載進(jìn)度
    Response.AddHeader("Content-Length", file.Length.ToString());
    // 指定返回的是一個(gè)不能被客戶端讀取的流,必須被下載
    Response.ContentType = "application/ms-excel";
    // 把文件流發(fā)送到客戶端
    Response.WriteFile(file.FullName);
    // 停止頁面的執(zhí)行
    Response.End();
    }
    導(dǎo)入、導(dǎo)出EXCEL中的一些問題匯總
    一、在項(xiàng)目中的添加引用:
    右擊項(xiàng)目資源管理器的引用-->添加引用-->選擇.NET選項(xiàng)卡-->選擇Microsoft.Office.Interop.Excel-->確定(如下圖);
    在選擇時(shí)注意一下.NET組件的版本號,圖是的12.0.0.0是Office2007的版本:
    二、在項(xiàng)目中使用Microsoft.Office.Interop.Excel:
    如果想使用Microsoft.Office.Interop.Excel,首先需要在項(xiàng)目中引用命名空間:
    using Microsoft.Office.Interop.Excel;
    三、建立Excel.Application相關(guān)對象
    //建立Application對象
    Microsoft.Office.Interop.Excel.Application myExcel = new Application();
    //建立Workbooks對象
    Workbooks myBooks = myExcel.Application.Workbooks;
    //建立一個(gè)System.Reflection.Missing的object對象
    object oMissing = System.Reflection.Missing.Value;
    四、打開或新建Excel的book文件
    //打開Excel文件,注意里的“ExccelFilePath”為Excel文件在服務(wù)器上的物理地址,包括文件名
    Workbook myBook = myBooks.Open(ExccelFilePath,oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);
    //新建Workseet對象,,此處為要操作的工作表 ,當(dāng)前要操作的工作表的獲取方法有兩種:使用工作表的索引值或使用工作表的名稱,名稱默認(rèn)為:“sheet1”/“Sheet2”等
    Worksheet mySheet = (Worksheet)myBook.Worksheets[1];
    //如果是新建EXCEL工作簿,需要 設(shè)置如下兩行內(nèi)容,以保證工作簿中有一個(gè)工作表,
    Workbook workbook1 = excel1.Workbooks.Add(true);
    Worksheet mySheet= (Worksheet)workbook1.Worksheets["sheet1"];
    //設(shè)置EXCEL對象是否顯示界面,默認(rèn)為false不顯示界面
    myExcel.Visble=true;
    五、一些比較重要的針對Excel的操作
    1、獲取Range對象
    ①、獲取一個(gè)單元格的Range對象:
    //選擇第一行、第一列的單元的單元格為Range對象
    Range r = (Excel.Range)mySheet.Cells[1, 1];
    //選擇多個(gè)連續(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;
    ③、給單元格設(shè)置邊框
    mySheet.Cells[2, 1].BorderAround(XlLineStyle.xlContinuous, XlBorderWeight.xlThin, XlColorIndex.xlColorIndexAutomatic, null);//畫線
    ④、合并單元格
    //合并單元格前先要將要合并的單元格選擇為Range對象
    Range r=Range.get_Range("A1:F3");
    //然后現(xiàn)設(shè)置合并單元格
    r.MergeCells = true;
    ⑤、設(shè)置單元格的字體、字號、背景色等屬性
    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);//設(shè)置顏色
    ⑥、刪除一行:
    //首先獲取要刪除的行的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 進(jìn)程
    關(guān)于這方面內(nèi)容有好多網(wǎng)友都在講多種方法,經(jīng)過本人實(shí)踐,以下方面才能真正做到結(jié)束EXCEL的任務(wù)進(jìn)程:
    1、將所有以上對EXCEL的操作放到一個(gè)方法中,
    2、在操作EXCEL后,即時(shí)將不使用對象一一釋放并賦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、再新建一個(gè)方法,并以該方法中執(zhí)行上面新建的操作EXCEL方法,并在執(zhí)行完操作EXCEL方法的后面添加GC.Collect():
    //下面方法中OutPutEXCEL()方法是輸出EXCEL文件的對EXCEL 操作的方法
    private void killExcel()
    {
    outPutEXCEL();
    GC.Collect();
    GC.WaitForPendingFinalizers();
    }
    好多網(wǎng)友都在介紹使用GC.Collect()釋放EXCEL占用的資源來結(jié)束EXCEL進(jìn)行,如果將“GC.Collect();”與操作EXCEL的業(yè)務(wù)寫在一個(gè)程序塊中,“GC”是永遠(yuǎn)不能結(jié)束EXCEL進(jìn)程的,在WEB應(yīng)用程序中,這種現(xiàn)象是很可怕的事情。原因是GC不會清理本程序塊中的垃圾內(nèi)存的。
    4、在業(yè)務(wù)事件中調(diào)用killEXCEL()方法:
    protected void LinkButton3_Click(object sender, EventArgs e)
    {
    //導(dǎo)出EXCEL
    killExcel();
    }
    八、一些權(quán)限的基本設(shè)置:
    使用以上方法在開發(fā)環(huán)境中調(diào)試程序沒有一點(diǎn)問題,等發(fā)布到服務(wù)器上后,程序還是不能正常運(yùn)行,需要進(jìn)行如下的權(quán)限設(shè)置:
    1、.NET導(dǎo)出Excel遇到的80070005錯誤的解決方法:
    檢索 COM 類工廠中 CLSID 為 {00024500-0000-0000-C000-000000000046}的組件時(shí)失敗,原因是出現(xiàn)以下錯誤: 80070005基本上.net導(dǎo)出excel文件,都需要如此配置一下,不配置有的時(shí)候沒錯,而配置后基本應(yīng)該不會出錯。
    具體配置方法如下:
    1:在服務(wù)器上安裝office的Excel軟件.
    2:在"開始"->"運(yùn)行"中輸入dcomcnfg.exe啟動"組件服務(wù)"
    3:依次雙擊"組件服務(wù)"->"計(jì)算機(jī)"->"我的電腦"->"DCOM配置"
    4:在"DCOM配置"中找到"Microsoft Excel 應(yīng)用程序",在它上面點(diǎn)擊右鍵,然后點(diǎn)擊"屬性",彈出"Microsoft Excel 應(yīng)用程序?qū)傩?對話框
    5:點(diǎn)擊"標(biāo)識"標(biāo)簽,選擇"交互式用戶"
    6:點(diǎn)擊"安全"標(biāo)簽,在"啟動和激活權(quán)限"上點(diǎn)擊"自定義",然后點(diǎn)擊對應(yīng)的"編輯"按鈕,在彈出的"安全性"對話框中填加一個(gè)"NETWORK SERVICE"用戶(注意要選擇本計(jì)算機(jī)名),并給它賦予"本地啟動"和"本地激活"權(quán)限.
    7:依然是"安全"標(biāo)簽,在"訪問權(quán)限"上點(diǎn)擊"自定義",然后點(diǎn)擊"編輯",在彈出的"安全性"對話框中也填加一個(gè)"NETWORK SERVICE"用戶,然后賦予"本地訪問"權(quán)限.
    8.如果交互式用戶設(shè)置后出現(xiàn)錯誤8000401a,可取消交互式用戶,指定為administratr,可暫時(shí)解決此問題。進(jìn)一步的解決方式還有待探討。
    9.采用第8點(diǎn)的設(shè)置后,打開Excel可能會出現(xiàn)“無法使用對象引用或鏈接”,并且不能進(jìn)行單元格粘貼。原因不明,取消設(shè)置后即可消失。
    以上是本人在近期作開發(fā)時(shí)的一點(diǎn)心得,現(xiàn)整理成文檔,供奮戰(zhàn)在程序開發(fā)一線的朋友共享,愿看到的網(wǎng)友能名幫助解決“無法使用對象引用或鏈接”的問題。