<span id="mktg5"></span>

<i id="mktg5"><meter id="mktg5"></meter></i>

        <label id="mktg5"><meter id="mktg5"></meter></label>
        最新文章專題視頻專題問答1問答10問答100問答1000問答2000關鍵字專題1關鍵字專題50關鍵字專題500關鍵字專題1500TAG最新視頻文章推薦1 推薦3 推薦5 推薦7 推薦9 推薦11 推薦13 推薦15 推薦17 推薦19 推薦21 推薦23 推薦25 推薦27 推薦29 推薦31 推薦33 推薦35 推薦37視頻文章20視頻文章30視頻文章40視頻文章50視頻文章60 視頻文章70視頻文章80視頻文章90視頻文章100視頻文章120視頻文章140 視頻2關鍵字專題關鍵字專題tag2tag3文章專題文章專題2文章索引1文章索引2文章索引3文章索引4文章索引5123456789101112131415文章專題3
        問答文章1 問答文章501 問答文章1001 問答文章1501 問答文章2001 問答文章2501 問答文章3001 問答文章3501 問答文章4001 問答文章4501 問答文章5001 問答文章5501 問答文章6001 問答文章6501 問答文章7001 問答文章7501 問答文章8001 問答文章8501 問答文章9001 問答文章9501
        當前位置: 首頁 - 科技 - 知識百科 - 正文

        C#數據導入/導出Excel文件及winForm導出Execl總結

        來源:懂視網 責編:小采 時間:2020-11-27 22:41:50
        文檔

        C#數據導入/導出Excel文件及winForm導出Execl總結

        C#數據導入/導出Excel文件及winForm導出Execl總結:一、asp.net中導出Execl的方法: 在asp.net中導出Execl有兩種方法,一種是將導出的文件存放在服務器某個文件夾下面,然后將文件地址輸出在瀏覽器上;一種是將文件直接將文件輸出流寫給瀏覽器。在Response輸出時,\t分隔的數據,導出execl時,等價于分列
        推薦度:
        導讀C#數據導入/導出Excel文件及winForm導出Execl總結:一、asp.net中導出Execl的方法: 在asp.net中導出Execl有兩種方法,一種是將導出的文件存放在服務器某個文件夾下面,然后將文件地址輸出在瀏覽器上;一種是將文件直接將文件輸出流寫給瀏覽器。在Response輸出時,\t分隔的數據,導出execl時,等價于分列

        一、asp.net中導出Execl的方法:

        在asp.net中導出Execl有兩種方法,一種是將導出的文件存放在服務器某個文件夾下面,然后將文件地址輸出在瀏覽器上;一種是將文件直接將文件輸出流寫給瀏覽器。在Response輸出時,\t分隔的數據,導出execl時,等價于分列,\n等價于換行。

        1、將整個html全部輸出execl

        此法將html中所有的內容,如按鈕,表格,圖片等全部輸出到Execl中。
        代碼如下:
        Response.Clear();
        Response.Buffer= true;
        Response.AppendHeader("Content-Disposition","attachment;filename="+DateTime.Now.ToString("yyyyMMdd")+".xls");
        Response.ContentEncoding=System.Text.Encoding.UTF8;
        Response.ContentType = "application/vnd.ms-excel";
        this.EnableViewState = false;
         
        這里我們利用了ContentType屬性,它默認的屬性為text/html,這時將輸出為超文本,即我們常見的網頁格式到客戶端,如果改為ms-excel將將輸出excel格式,也就是說以電子表格的格式輸出到客戶端,這時瀏覽器將提示你下載保存。ContentType的屬性還包括:image/JPEG;text/HTML;image/GIF;vnd.ms-excel/msword 。同理,我們也可以輸出(導出)圖片、word文檔等。下面的方法,也均用了這個屬性。

        2、將DataGrid控件中的數據導出Execl

        上述方法雖然實現了導出的功能,但同時把按鈕、分頁框等html中的所有輸出信息導了進去。而我們一般要導出的是數據,DataGrid控件上的數據。
        代碼如下:
        System.Web.UI.Control ctl=this.DataGrid1;
        //DataGrid1是你在窗體中拖放的控件
        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";
        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();

        如果你的DataGrid用了分頁,它導出的是當前頁的信息,也就是它導出的是DataGrid中顯示的信息。而不是你select語句的全部信息。

        為方便使用,寫成方法如下:
        代碼如下:
        public void DGToExcel(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";
        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();
        }

        用法:DGToExcel(datagrid1);

        3、將DataSet中的數據導出Execl

        有了上邊的思路,就是將在導出的信息,輸出(Response)客戶端,這樣就可以導出了。那么把DataSet中的數據導出,也就是把DataSet中的表中的各行信息,以ms-excel的格式Response到http流,這樣就OK了。說明:參數ds應為填充有數據表的DataSet,文件名是全名,包括后綴名,如execl2006.xls
        代碼如下:
        public void CreateExcel(DataSet ds,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="";

        //定義表對象與行對象,同時用DataSet對其值進行初始化
        DataTable dt=ds.Tables[0];
        DataRow[] myRow=dt.Select();//可以類似dt.Select("id>10")之形式達到數據篩選目的
        int i=0;
        int cl=dt.Columns.Count;


        //取得數據表各列標題,各標題之間以\t分割,最后一個列標題后加回車符
        for(i=0;i<cl;i++)
        {
        if(i==(cl-1))//最后一列,加\n
        {
        colHeaders +=dt.Columns[i].Caption.ToString() +"\n";
        }
        else
        {
        colHeaders+=dt.Columns[i].Caption.ToString()+"\t";
        }

        }
        resp.Write(colHeaders);
        //向HTTP輸出流中寫入取得的數據信息

        //逐行處理數據
        foreach(DataRow row in myRow)
        {
        //當前行數據寫入HTTP輸出流,并且置空ls_item以便下行數據
        for(i=0;i<cl;i++)
        {
        if(i==(cl-1))//最后一列,加\n
        {
        ls_item +=row[i].ToString()+"\n";
        }
        else
        {
        ls_item+=row[i].ToString()+"\t";
        }

        }
        resp.Write(ls_item);
        ls_item="";

        }
        resp.End();
        }

        4、將dataview導出execl

        若想實現更加富于變化或者行列不規則的execl導出時,可用本法。   
        代碼如下:
        public void OutputExcel(DataView dv,string str)
        {
        //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;
        // 添加頭信息,為"文件下載/另存為"對話框指定默認文件名
        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();
        }


        上面的方面,均將要導出的execl數據,直接給瀏覽器輸出文件流,下面的方法是首先將其存到服務器的某個文件夾中,然后把文件發送到客戶端。這樣可以持久的把導出的文件存起來,以便實現其它功能。

        5、將execl文件導出到服務器上,再下載。

        二、winForm中導出Execl的方法:

        1、方法1:
        代碼如下:
        public void Out2Excel(string sTableName,string url)
        {
        Excel.Application oExcel=new Excel.Application();
        Workbooks oBooks;
        Workbook oBook;
        Sheets oSheets;
        Worksheet oSheet;
        Range oCells;
        string sFile="",sTemplate="";
        //
        System.Data.DataTable dt=TableOut(sTableName).Tables[0];

        sFile=url+"\\myExcel.xls";
        sTemplate=url+"\\MyTemplate.xls";
        //
        oExcel.Visible=false;
        oExcel.DisplayAlerts=false;
        //定義一個新的工作簿
        oBooks=oExcel.Workbooks;
        oBooks.Open(sTemplate,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing, Type.Missing, Type.Missing);
        oBook=oBooks.get_Item(1);
        oSheets=oBook.Worksheets;
        oSheet=(Worksheet)oSheets.get_Item(1);
        //命名該sheet
        oSheet.Name="Sheet1";

        oCells=oSheet.Cells;
        //調用dumpdata過程,將數據導入到Excel中去
        DumpData(dt,oCells);
        //保存
        oSheet.SaveAs(sFile,Excel.XlFileFormat.xlTemplate,Type.Missing,Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing);
        oBook.Close(false, Type.Missing,Type.Missing);
        //退出Excel,并且釋放調用的COM資源
        oExcel.Quit();

        GC.Collect();
        KillProcess("Excel");
        }

        private void KillProcess(string processName)
        {
        System.Diagnostics.Process myproc= new System.Diagnostics.Process();
        //得到所有打開的進程
        try
        {
        foreach (Process thisproc in Process.GetProcessesByName(processName))
        {
        if(!thisproc.CloseMainWindow())
        {
        thisproc.Kill();
        }
        }
        }
        catch(Exception Exc)
        {
        throw new Exception("",Exc);
        }
        }

        2、方法2:
        代碼如下:
        protected void ExportExcel()
        {
        gridbind();

        if(ds1==null) return;

        string saveFileName="";
        // bool fileSaved=false;
        SaveFileDialog saveDialog=new SaveFileDialog();
        saveDialog.DefaultExt ="xls";
        saveDialog.Filter="Excel文件|*.xls";
        saveDialog.FileName ="Sheet1";
        saveDialog.ShowDialog();
        saveFileName=saveDialog.FileName;
        if(saveFileName.IndexOf(":")<0) return; //被點了取消
        // excelapp.Workbooks.Open (App.path & \\工程進度表.xls)


        Excel.Application xlApp=new Excel.Application();
        object missing=System.Reflection.Missing.Value;


        if(xlApp==null)
        {
        MessageBox.Show("無法創建Excel對象,可能您的機子未安裝Excel");
        return;
        }
        Excel.Workbooks workbooks=xlApp.Workbooks;
        Excel.Workbook workbook=workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
        Excel.Worksheet worksheet=(Excel.Worksheet)workbook.Worksheets[1];//取得sheet1
        Excel.Range range;


        string oldCaption=Title_label .Text.Trim ();
        long totalCount=ds1.Tables[0].Rows.Count;
        long rowRead=0;
        float percent=0;

        worksheet.Cells[1,1]=Title_label .Text.Trim ();
        //寫入字段
        for(int i=0;i<ds1.Tables[0].Columns.Count;i++)
        {
        worksheet.Cells[2,i+1]=ds1.Tables[0].Columns.ColumnName;
        range=(Excel.Range)worksheet.Cells[2,i+1];
        range.Interior.ColorIndex = 15;
        range.Font.Bold = true;

        }
        //寫入數值
        Caption .Visible = true;
        for(int r=0;r<ds1.Tables[0].Rows.Count;r++)
        {
        for(int i=0;i<ds1.Tables[0].Columns.Count;i++)
        {
        worksheet.Cells[r+3,i+1]=ds1.Tables[0].Rows[r];
        }
        rowRead++;
        percent=((float)(100*rowRead))/totalCount;
        this.Caption.Text= "正在導出數據["+ percent.ToString("0.00") +"%]...";
        Application.DoEvents();
        }
        worksheet.SaveAs(saveFileName,missing,missing,missing,missing,missing,missing,missing,missing);

        this.Caption.Visible= false;
        this.Caption.Text= oldCaption;

        range=worksheet.get_Range(worksheet.Cells[2,1],worksheet.Cells[ds1.Tables[0].Rows.Count+2,ds1.Tables[0].Columns.Count]);
        range.BorderAround(Excel.XlLineStyle.xlContinuous,Excel.XlBorderWeight.xlThin,Excel.XlColorIndex.xlColorIndexAutomatic,null);

        range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].ColorIndex = Excel.XlColorIndex.xlColorIndexAutomatic;
        range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].LineStyle =Excel.XlLineStyle.xlContinuous;
        range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].Weight =Excel.XlBorderWeight.xlThin;

        if(ds1.Tables[0].Columns.Count>1)
        {
        range.Borders[Excel.XlBordersIndex.xlInsideVertical].ColorIndex=Excel.XlColorIndex.xlColorIndexAutomatic;
        }
        workbook.Close(missing,missing,missing);
        xlApp.Quit();
        }



        三、附注:

        雖然都是實現導出execl的功能,但在asp.net和winform的程序中,實現的代碼是各不相同的。在asp.net中,是在服務器端讀取數據,在服務器端把數據以ms-execl的格式,以Response輸出到瀏覽器(客戶端);而在winform中,是把數據讀到客戶端(因為winform運行端就是客戶端),然后調用客戶端安裝的office組件,將讀到的數據寫在execl的工作簿中。
        代碼如下:
        SqlConnection conn=new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["conn"]);
        SqlDataAdapter da=new SqlDataAdapter("select * from tb1",conn);
        DataSet ds=new DataSet();
        da.Fill(ds,"table1");
        DataTable dt=ds.Tables["table1"];
        string name=System.Configuration.ConfigurationSettings.AppSettings["downloadurl"].ToString()+DateTime.Today.ToString("yyyyMMdd")+new Random(DateTime.Now.Millisecond).Next(10000).ToString()+".csv";//存放到web.config中downloadurl指定的路徑,文件格式為當前日期+4位隨機數
        FileStream fs=new FileStream(name,FileMode.Create,FileAccess.Write);
        StreamWriter sw=new StreamWriter(fs,System.Text.Encoding.GetEncoding("gb2312"));
        sw.WriteLine("自動編號,姓名,年齡");
        foreach(DataRow dr in dt.Rows)
        {
        sw.WriteLine(dr["ID"]+","+dr["vName"]+","+dr["iAge"]);
        }
        sw.Close();
        Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(name));
        Response.ContentType = "application/ms-excel";// 指定返回的是一個不能被客戶端讀取的流,必須被下載
        Response.WriteFile(name); // 把文件流發送到客戶端
        Response.End();

        聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com

        文檔

        C#數據導入/導出Excel文件及winForm導出Execl總結

        C#數據導入/導出Excel文件及winForm導出Execl總結:一、asp.net中導出Execl的方法: 在asp.net中導出Execl有兩種方法,一種是將導出的文件存放在服務器某個文件夾下面,然后將文件地址輸出在瀏覽器上;一種是將文件直接將文件輸出流寫給瀏覽器。在Response輸出時,\t分隔的數據,導出execl時,等價于分列
        推薦度:
        • 熱門焦點

        最新推薦

        猜你喜歡

        熱門推薦

        專題
        Top
        主站蜘蛛池模板: 热99re久久免费视精品频软件| 中文字幕免费在线看线人动作大片 | 亚洲a级成人片在线观看| 一区二区在线免费观看| 亚洲AV日韩AV永久无码下载| 热久久这里是精品6免费观看| 亚洲区小说区图片区QVOD| 国产又黄又爽又大的免费视频| 亚洲熟妇av一区二区三区| 免费无码又爽又刺激网站直播| 亚洲AV无码乱码国产麻豆| 污污网站18禁在线永久免费观看| 亚洲国产香蕉碰碰人人| 久久久久久精品成人免费图片| 91亚洲国产成人久久精品网址| 色窝窝免费一区二区三区| 亚洲中文字幕无码mv| 免费在线不卡视频| 国产久爱免费精品视频| 久久精品7亚洲午夜a| 无码av免费毛片一区二区| 亚洲精品国产首次亮相| 日韩亚洲国产二区| 久久久久国产精品免费看| 亚洲kkk4444在线观看| 亚洲国产高清在线一区二区三区| 中文字幕免费在线看| 亚洲一二成人精品区| 最新仑乱免费视频| 亚洲免费日韩无码系列| 亚洲精品免费视频| 大学生高清一级毛片免费| 国产精品免费久久| 亚洲成aⅴ人片在线观| 亚洲成人影院在线观看| 8090在线观看免费观看| 看免费毛片天天看| 亚洲精品福利网泷泽萝拉| 亚洲国产精品成人| 两性刺激生活片免费视频| 日韩在线视频免费|