c# datagridview匯出到excel【轉載】

來源:互聯網
上載者:User
c# datagridview匯出到excel【轉載】
http://hi.baidu.com/weizier/blog/item/8212caea1123b4d6d439c9fe.html

方法一:添加dll引用

右擊選擇你所在的項目的“引用”,選擇“添加引用”。

彈出“添加引用”對話方塊。

選擇“COM”選項卡。

選擇“Microsoft Excel 11.0 Object Library”

單擊“確定”按鈕。

代碼

public static bool ExportForDataGridview(DataGridView gridView, string fileName, bool isShowExcle)
        {

            //建立Excel對象

            Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
            try
            {
                if (app == null)
                {
                    return false;
                }
               
                app.Visible = isShowExcle;
                Workbooks workbooks = app.Workbooks;
                _Workbook workbook = workbooks.Add(XlWBATemplate.xlWBATWorksheet);
                Sheets sheets = workbook.Worksheets;
                _Worksheet worksheet = (_Worksheet)sheets.get_Item(1);
                if (worksheet == null)
                {
                    return false;
                }
                string sLen = "";
                //取得最後一列列名
                char H = (char)(64 + gridView.ColumnCount / 26);
                char L = (char)(64 + gridView.ColumnCount % 26);
                if (gridView.ColumnCount < 26)
                {
                    sLen = L.ToString();
                }
                else
                {
                    sLen = H.ToString() + L.ToString();
                }

                //標題
                string sTmp = sLen + "1";
                Range ranCaption = worksheet.get_Range(sTmp, "A1");
                string[] asCaption = new string[gridView.ColumnCount];
                for (int i = 0; i < gridView.ColumnCount; i++)
                {
                    asCaption[i] = gridView.Columns[i].HeaderText;
                }
                ranCaption.Value2 = asCaption;

                //資料
                object[] obj = new object[gridView.Columns.Count];
                for (int r = 0; r < gridView.RowCount - 1; r++)
                {
                    for (int l = 0; l < gridView.Columns.Count; l++)
                    {
                        if (gridView[l, r].ValueType == typeof(DateTime))
                        {
                            obj[l] = gridView[l, r].Value.ToString();
                        }
                        else
                        {
                            obj[l] = gridView[l, r].Value;
                        }
                    }
                    string cell1 = sLen + ((int)(r + 2)).ToString();
                    string cell2 = "A" + ((int)(r + 2)).ToString();
                    Range ran = worksheet.get_Range(cell1, cell2);
                    ran.Value2 = obj;
                }
                //儲存
                workbook.SaveCopyAs(fileName);
                workbook.Saved = true;
            }
            finally
            {
                //關閉
                app.UserControl = false;
                app.Quit();
            }
            return true;

        }

方法二

用流儲存成xls檔案. 這種方法比較好,不用引用Excel組件.   下面是具體例子,可以參考

using System.IO;

       

        /// <summary>

        /// 另存新檔按鈕

        /// </summary>

        private void SaveAs() //另存新檔按鈕   匯出成Excel

        {

            SaveFileDialog saveFileDialog = new SaveFileDialog();

            saveFileDialog.Filter = "Execl files (*.xls)|*.xls";

            saveFileDialog.FilterIndex = 0;

            saveFileDialog.RestoreDirectory = true;

            saveFileDialog.CreatePrompt = true;

            saveFileDialog.Title = "Export Excel File To";

            saveFileDialog.ShowDialog();

            Stream myStream;

            myStream = saveFileDialog.OpenFile();

            //StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding("gb2312"));

            StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));

            string str = "";

            try

            {

                //寫標題

                for (int i = 0; i < dgvAgeWeekSex.ColumnCount; i++)

                {

                    if (i > 0)

                    {

                        str += "\t";

                    }

                    str += dgvAgeWeekSex.Columns[i].HeaderText;

                }

                sw.WriteLine(str);

                //寫內容

                for (int j = 0; j < dgvAgeWeekSex.Rows.Count; j++)

                {

                    string tempStr = "";

                    for (int k = 0; k < dgvAgeWeekSex.Columns.Count; k++)

                    {

                        if (k > 0)

                        {

                            tempStr += "\t";

                        }

                        tempStr += dgvAgeWeekSex.Rows[j].Cells[k].Value.ToString();

                    }

                   

                    sw.WriteLine(tempStr);                    

                }

                sw.Close();

                myStream.Close();

            }

            catch (Exception e)

            {

                MessageBox.Show(e.ToString());

            }

            finally

            {

                sw.Close();

                myStream.Close();

            }          

      }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.