码迷,mamicode.com
首页 > Windows程序 > 详细

c# 从DataGridVieew导出到excel

时间:2017-12-12 22:24:31      阅读:261      评论:0      收藏:0      [点我收藏+]

标签:idv   work   pos   nbsp   als   object   bsp   ==   template   

public static bool DataGridViewToExcel(DataGridView dataGridView, bool isShowExcel)

        {

 

            int rowsQty = dataGridView.Rows.Count;

            int colsQty = dataGridView.Columns.Count;

            int colIndex = 0;

 

            if (rowsQty == 0)

            {

                return false;

            }

 

            Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();

            Microsoft.Office.Interop.Excel.Workbook workbook = excel.Workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);

            Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];

            excel.Visible = isShowExcel;

 

 

 

            foreach (DataGridViewColumn col in dataGridView.Columns)

            {

                colIndex++;

                excel.Cells[1, colIndex] = col.Name;

            }

 

            object[,] objData = new object[rowsQty, colsQty];

 

            for (int r = 0; r < rowsQty; r++)

            {

                for (int c = 0; c < colsQty; c++)

                {

                    objData[r, c] = dataGridView.Rows[r].Cells[c].Value;

                }

            }

 

            Microsoft.Office.Interop.Excel.Range myRange;

            myRange = worksheet.Range[excel.Cells[2, 1], excel.Cells[rowsQty + 1, colsQty]];

            myRange.Value2 = objData;

 

            return true;

        }

c# 从DataGridVieew导出到excel

标签:idv   work   pos   nbsp   als   object   bsp   ==   template   

原文地址:http://www.cnblogs.com/3xin/p/8028460.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!