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è)置標題格式為居中對齊
    }
    //
    //取得表格中的數(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();
    }
    }
    }
    //
    //加載一個合計行
    //
    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;
    //
    //設(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è)置為淺黃色,共計有56種
    //
    //取得整個報表的標題
    //
    excel.Cells[2,2] = str;
    //
    //設(shè)置整個報表的標題格式
    //
    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è)置報表表格為最適應寬度
    //
    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è)置整個報表的標題為跨列居中
    //
    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;
    // 添加頭信息,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";
    // 把文件流發(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相關(guān)對象
    //建立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文件在服務(wù)器上的物理地址,包括文件名
    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工作簿,需要 設(shè)置如下兩行內(nèi)容,以保證工作簿中有一個工作表,
    Workbook workbook1 = excel1.Workbooks.Add(true);
    Worksheet mySheet= (Worksheet)workbook1.Worksheets["sheet1"];
    //設(shè)置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;
    ③、給單元格設(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 進程
    關(guān)于這方面內(nèi)容有好多網(wǎng)友都在講多種方法,經(jīng)過本人實踐,以下方面才能真正做到結(jié)束EXCEL的任務(wù)進程:
    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è)務(wù)寫在一個程序塊中,“GC”是永遠不能結(jié)束EXCEL進程的,在WEB應用程序中,這種現(xiàn)象是很可怕的事情。原因是GC不會清理本程序塊中的垃圾內(nèi)存的。
    4、在業(yè)務(wù)事件中調(diào)用killEXCEL()方法:
    protected void LinkButton3_Click(object sender, EventArgs e)
    {
    //導出EXCEL
    killExcel();
    }
    八、一些權(quán)限的基本設(shè)置:
    使用以上方法在開發(fā)環(huán)境中調(diào)試程序沒有一點問題,等發(fā)布到服務(wù)器上后,程序還是不能正常運行,需要進行如下的權(quán)限設(shè)置:
    1、.NET導出Excel遇到的80070005錯誤的解決方法:
    檢索 COM 類工廠中 CLSID 為 {00024500-0000-0000-C000-000000000046}的組件時失敗,原因是出現(xiàn)以下錯誤: 80070005基本上.net導出excel文件,都需要如此配置一下,不配置有的時候沒錯,而配置后基本應該不會出錯。
    具體配置方法如下:
    1:在服務(wù)器上安裝office的Excel軟件.
    2:在"開始"->"運行"中輸入dcomcnfg.exe啟動"組件服務(wù)"
    3:依次雙擊"組件服務(wù)"->"計算機"->"我的電腦"->"DCOM配置"
    4:在"DCOM配置"中找到"Microsoft Excel 應用程序",在它上面點擊右鍵,然后點擊"屬性",彈出"Microsoft Excel 應用程序?qū)傩?對話框
    5:點擊"標識"標簽,選擇"交互式用戶"
    6:點擊"安全"標簽,在"啟動和激活權(quán)限"上點擊"自定義",然后點擊對應的"編輯"按鈕,在彈出的"安全性"對話框中填加一個"NETWORK SERVICE"用戶(注意要選擇本計算機名),并給它賦予"本地啟動"和"本地激活"權(quán)限.
    7:依然是"安全"標簽,在"訪問權(quán)限"上點擊"自定義",然后點擊"編輯",在彈出的"安全性"對話框中也填加一個"NETWORK SERVICE"用戶,然后賦予"本地訪問"權(quán)限.
    8.如果交互式用戶設(shè)置后出現(xiàn)錯誤8000401a,可取消交互式用戶,指定為administratr,可暫時解決此問題。進一步的解決方式還有待探討。
    9.采用第8點的設(shè)置后,打開Excel可能會出現(xiàn)“無法使用對象引用或鏈接”,并且不能進行單元格粘貼。原因不明,取消設(shè)置后即可消失。
    以上是本人在近期作開發(fā)時的一點心得,現(xiàn)整理成文檔,供奮戰(zhàn)在程序開發(fā)一線的朋友共享,愿看到的網(wǎng)友能名幫助解決“無法使用對象引用或鏈接”的問題。