把DatagridView中的數據導出到Excel中

 private void ExportExcel(DataGridView dataGridViewControlName)//把DatagridView中的數據導出到Excel中,首先要添加引用 Microsoft.Office.Interop.Excel
        {
            if (dataGridViewControlName == null || dataGridViewControlName.Rows.Count == 0) return;
            Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
            if (xlApp == null)
            {
                return;
            }
            System.Globalization.CultureInfo CurrentCI = System.Threading.Thread.CurrentThread.CurrentCulture;
            System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
            Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;
            Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
            Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];
            Microsoft.Office.Interop.Excel.Range range;
            long totalCount = dataGridViewControlName.Rows.Count;
            long rowRead = 0;
            float percent = 0;
            for (int i = 0; i < dataGridViewControlName.Columns.Count; i++)
            {
                worksheet.Cells[1, i + 1] = dataGridViewControlName.Columns[i].HeaderText;
                range = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[1, i + 1];
                range.Interior.ColorIndex = 15;
                range.Font.Bold = true;
            }
            for (int r = 0; r < dataGridViewControlName.Rows.Count; r++)
            {
                for (int i = 0; i < dataGridViewControlName.Columns.Count; i++)
                {
                    if (dataGridViewControlName.Rows[r].Cells[i].Value == null)
                    {
                        worksheet.Cells[r + 2, i + 1] = "";
                    }
                    else
                    {
                        worksheet.Cells[r + 2, i + 1] = dataGridViewControlName.Rows[r].Cells[i].Value.ToString();
                    }
                }
                rowRead++;
                percent = ((float)(100 * rowRead)) / totalCount;
            }
            xlApp.Visible = true;
        }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章