datagridview 导出Excel文件

 
 /// <summary>
        /// 以datagridview 导出Excel文件   
        /// </summary>
        /// <param name="dt"></param>
        public void ExportExcel(DataGridView dgv)
        {
            if (dgv.Rows.Count==0) return;
            Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
            if (xlApp == null)
            {
                MessageBox.Show("无法创建Excel对象,可能您的机子未安装Excel", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            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];//取得Sheet1
            Microsoft.Office.Interop.Excel.Range range;
            long totalCount = dgv.Rows.Count;
            long rowRead = 0;
            float percent = 0;
            //写入字段
            for (int i = 0; i < dgv.Columns.Count; i++)
            {
                worksheet.Cells[1, i + 1] = dgv.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 < dgv.Rows.Count; r++)
            {
                for (int i = 0; i < dgv.Columns.Count; i++)
                {
                    if (dgv[i, r].ValueType == typeof(string))   
                {
                    worksheet.Cells[r + 2, i + 1] = "'" + dgv[i, r].Value.ToString();  
                }   
                else  
                {
                    worksheet.Cells[r + 2, i+ 1] = dgv[i, r].Value.ToString();   
                }  
                }
                rowRead++;
                percent = ((float)(100 * rowRead)) / totalCount;
            }
            xlApp.Visible = true;
        }


你可能感兴趣的:(String,Excel,null,float)