C#WinForm 直接匯出DataGridView資料到Excel表格的二種方法對比

來源:互聯網
上載者:User

標籤:datagridview   excel匯出   

方法一、利用微軟的excel 操作類

 

引用:using Excel = Microsoft.Office.Interop.Excel;

 

代碼如下:

        #region匯出資料表:Excle (微軟的excel 操作類)        ///<summary>        ///匯出資料表:Excle        ///</summary>        ///<param name="myDGV"></param>        public void _ToExcel(DataGridView myDGV)        {            string path = "";            SaveFileDialog saveDialog = new SaveFileDialog();            saveDialog.DefaultExt = "xlsx";            saveDialog.Filter = "Excel檔案|*.xlsx";            saveDialog.ShowDialog();            path = saveDialog.FileName;            if (path.IndexOf(":") < 0) return; //判斷是否點擊取消            try            {                Excel.Application xlApp = new Excel.Application();                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                int colIndex = 0;                //寫入標題                for (int i = 0; i < myDGV.ColumnCount; i++)                {                    if (myDGV.Columns[i].Visible)//用作於不匯出隱藏列                    {                        colIndex++;                        worksheet.Cells[1, colIndex] = myDGV.Columns[i].HeaderText;                        //worksheet.Cells[1, i] = myDGV.Columns[i].HeaderText;                    }                }                //寫入數值                for (int r = 0; r < myDGV.Rows.Count - 1; r++)                {                    colIndex = 0;                    for (int i = 0; i < myDGV.ColumnCount; i++)                    {                        if (myDGV.Columns[i].Visible)                        {                            colIndex++;                            worksheet.Cells[r + 2, colIndex] = myDGV.Rows[r].Cells[i].Value;                        }                    }                    System.Windows.Forms.Application.DoEvents();                }                worksheet.Columns.EntireColumn.AutoFit();//列寬自適應                if (path != "")                {                    try                    {                        workbook.Saved = true;                        workbook.SaveCopyAs(path);                        //fileSaved = true;                    }                    catch (Exception ex)                    {                        //fileSaved = false;                        MessageBox.Show("匯出檔案時出錯,檔案可能正被開啟!\n\r" + ex.Message);                    }                }                xlApp.Quit();                GC.Collect();//強行銷毀                // if (fileSaved && System.IO.File.Exists(saveFileName)) System.Diagnostics.Process.Start(saveFileName); //開啟EXCEL                 MessageBox.Show(path + ",匯出成功", "系統提示", MessageBoxButtons.OK);            }            catch (Exception ex)            {                MessageBox.Show(ex.Message);            }         }        #endregion

 

方法二、IO基礎流操作類

 

引用:using System.IO;

using System.Threading;

 

代碼如下:

        #region匯出資料表:Excle (io流操作類)        ///<summary>        ///匯出資料表:Excle (io流操作類)        ///</summary>        ///<param name="myDGV"></param>        public void _ToExcel2(DataGridView myDGV)        {            string path = "";            SaveFileDialog saveDialog = new SaveFileDialog();            saveDialog.DefaultExt = "xls";            saveDialog.Filter = "Excel97-2003 (*.xls)|*.xls|All Files (*.*)|*.*";            saveDialog.ShowDialog();            path = saveDialog.FileName;            if (path.IndexOf(":") < 0) return; //判斷是否點擊取消            try            {                Thread.Sleep(1000);                StreamWriter sw = new StreamWriter(path, false, Encoding.GetEncoding("gb2312"));                StringBuilder sb = new StringBuilder();                //寫入標題                for (int k = 0; k < myDGV.Columns.Count; k++)                {                    if (myDGV.Columns[k].Visible)//匯出可見的標題                    {                        //"\t"就等於鍵盤上的Tab,加個"\t"的意思是: 填充完後進入下一個儲存格.                        sb.Append(myDGV.Columns[k].HeaderText.ToString().Trim() + "\t");                    }                }                sb.Append(Environment.NewLine);//換行                //寫入每行數值                for (int i = 0; i < myDGV.Rows.Count - 1; i++)                {                    System.Windows.Forms.Application.DoEvents();                    for (int j = 0; j < myDGV.Columns.Count; j++)                    {                        if (myDGV.Columns[j].Visible)//匯出可見的儲存格                        {                            //注意儲存格有一定的位元組數量限制,如果超出,就會出現兩個儲存格的內容是一模一樣的.                            //具體限制是多少位元組,沒有作深入研究.                            sb.Append(myDGV.Rows[i].Cells[j].Value.ToString().Trim() + "\t");                        }                    }                    sb.Append(Environment.NewLine); //換行                }                sw.Write(sb.ToString());                sw.Flush();                sw.Close();                MessageBox.Show(path + ",匯出成功", "系統提示", MessageBoxButtons.OK);            }            catch (Exception ex)            {                MessageBox.Show(ex.Message);            }         }        #endregion

 

         二種方法對比,利用IO基礎流匯出到Excel表格中的速度最快。特別是上10萬行以上的資料,更是能體現其速度。

本文出自 “9212950” 部落格,請務必保留此出處http://9222950.blog.51cto.com/9212950/1607070

C#WinForm 直接匯出DataGridView資料到Excel表格的二種方法對比

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.